我正在尝试将我的Assets文件夹中的一些文件(以及创建一些新文件)复制到外部文件夹。
我知道我需要以下权限 -
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
然后,我应该检查外部存储状态如下(从android官方示例中使用的代码示例) -
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
然后,我可以使用getExternalFilesDir()
作为 -
String finalOutputFilePath = context.getExternalFilesDir(null) + "/" + databaseName;
它会将文件保存到某个地方,例如 - Android/data/myPackageName/files/
但是,我希望将文件存储在特定文件夹中,例如 -
所以,我的问题是如何选择(创建和使用)指定的文件夹?
P.S。 - 我想,这个问题可能已在SO上得到解答,但我找不到它。
答案 0 :(得分:1)
要创建文件夹,请使用createFolder方法。
private void createFolder(String folderName){
File file=new File(Environment.getExternalStorageDirectory() + File.separator +folderName);
if(!file.exists())
file.mkdirs();
}
private void CopyAssets(String folderName) {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("Files");
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
for(String filename : files) {
System.out.println("File name => "+filename);
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("Files/"+filename); // if files resides inside the "Files" directory itself
out = new FileOutputStream(Environment.getExternalStorageDirectory().toString()+File.separator +folderName +"/" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("tag", e.getMessage());
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}