У меня есть вопрос, который, вероятно, граничит с мнением, но у меня нет связанных вопросов или документации, на которые можно ответить, поэтому я чувствую, что это справедливый вопрос. Я пытаюсь создать приложение android, которое изменяет файлы musi c, и я хотел бы иметь общую папку, чтобы файлы и результаты могли быть доступны и доступны для общего доступа. Мне бы понравилось, если бы он был среди других папок, таких как Musi c, Downloads, Movies и т. Д. c или даже под Musi c, поскольку он связан с musi c. Тем не менее, похоже, что в Android нет защиты, нет, так как после того, как я что-то сделал и положил туда, мне нужно использовать намерение для доступа к нему снова, где, поскольку я предпочел бы просто открыть файлы и не иметь фиаско на основе разрешений. Возможно, можно использовать символическую ссылку типа c, например, Linux, которая указывает на внутреннюю папку моих приложений, но в этом я все еще не уверен. В любом случае, есть ли способ, которым я должен go об этом? Если да, есть ли какие-то ресурсы, на которые я мог бы указать?
Заранее спасибо всем, кто занялся этим!
Редактировать для CommonsWare:
Я использовал следующее чтобы создать папку: Файл mediaStorageDir = новый файл (Environment.getExternalStorageDirectory (), APP_NAME);
И это для копирования файлов из другого места туда:
public void copyFileToHomeDirectory(Uri uri)
{
try
{
ContentResolver contentResolver = getApplicationContext().getContentResolver();
String fileName = queryName(contentResolver, uri);
//Get file extension
String fileType = fileName.substring(fileName.length() - 4, fileName.length());
if(fileType.equalsIgnoreCase(MP3_EXTENSION))
{
String path = Environment.getExternalStorageDirectory() + APP_FOLDER;
InputStream in = contentResolver.openInputStream(uri);
File outputFile = new File(path + File.separator + fileName);
outputFile.createNewFile();
OutputStream out = new FileOutputStream(outputFile);
//First we crack open the file to copy it's contents:
byte[] buffer = new byte[KB_SIZE];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
in.close();
in = null;
// write the output file (You have now copied the file)
out.flush();
out.close();
out = null;
}
}
catch(FileNotFoundException fnfe)
{
Log.e(TAG, "FileNotFoundException");
Log.e(TAG, Log.getStackTraceString(fnfe));
}
catch(IOException ioe)
{
Log.e(TAG, "IOException");
Log.e(TAG, Log.getStackTraceString(ioe));
}
catch(Exception e)
{
Log.e(TAG, "General Exception");
Log.e(TAG, Log.getStackTraceString(e));
}
}
Я пробовал другие методы, которые я переписал в процессе, но доступ к файлам, которые будут использоваться снова, мне нужно что-то вроде этого:
public void openDirectory(View view)
{
// Choose a directory using the system's file picker.
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// Provide read access to files and sub-directories in the user-selected
// directory.
//intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
//intent.addCategory(Intent.CATEGORY_OPENABLE);
// Optionally, specify a URI for the directory that should be opened in
// the system file picker when it loads.
//intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, uriToLoad);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*"); //use image/* for photos, etc.
//The result of this code will be calling the onActivityResult function below
startActivityForResult(intent, REQUEST_MUSIC_DIR);
}
Edit2: я реорганизовал папки в соответствии с тем, что я должен делать что я могу работать с файлами свободно, однако, даже в моем внутреннем кеш-хранилище (getCacheDir () + имя_папки) либо не позволяет мне создавать файлы (outputFile.createNewFile не выдает ошибку), либо не позволяет я открываю их, когда я go получаю список каталогов.
Вот мой код для создания файла:
String path = getCacheDir() + MY_SUB_FOLDER;
//uri is obtained through ACTION_OPEN_DOCUMENT intent
InputStream in = contentResolver.openInputStream(uri);
File outputFile = new File(path + "/" + fileName);
outputFile.createNewFile();
Log.i(TAG, "The new file's directory/path is: " + outputFile.getAbsolutePath());
//NOTE: This is returning /data/user/0/com.example.myapplication/cache/MY_SUB_FOLDER/file_name.mp3
OutputStream out = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
Это мой код для попытки открыть и прочитать эти newl y созданные файлы
File directory = new File(getCacheDir(), MY_SUB_FOLDER);
Log.i(TAG, "This is the directory we're trying to get the files from: " + directory.getAbsolutePath());
//NOTE: This returns /data/user/0/com.example.myapplication/cache/MY_SUB_FOLDER
File[] files = directory.listFiles();
if(files != null)
{
for(int i = 0; i < files.length; i++)
{
Log.d(TAG, "Files found: " + files[i].getAbsolutePath());
}
}
Переменная files не равна нулю, но имеет длину 0 и файлы не найдены.
Edit3: я перехватываю исключения и регистрирую любые следы стека, которые в настоящее время ничего не возвращают.
catch(FileNotFoundException fnfe)
{
Log.i(TAG, "FileNotFoundException");
Log.i(TAG, Log.getStackTraceString(fnfe));
}
catch(IOException ioe)
{
Log.i(TAG, "IOException");
Log.i(TAG, Log.getStackTraceString(ioe));
}
catch(Exception e)
{
Log.i(TAG, "General Exception");
Log.i(TAG, Log.getStackTraceString(e));
}