Reputation: 1085
I am trying to copy some files from my Assets folder (and also create some new files) to an External folder.
I know that I will need following permissions -
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Then, I should check for the External Storage state as following (code sample used from android's official example)-
/* 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;
}
Then, I can use getExternalFilesDir()
as -
String finalOutputFilePath = context.getExternalFilesDir(null) + "/" + databaseName;
and it will save file to somewhere like - Android/data/myPackageName/files/
But, I want the files to be stored at a specific folder, for example -
So, my question is how to select (create & use) the specified folder?
P.S. - I guess, this question might have already been answered on SO, but I couldn't find it.
Upvotes: 1
Views: 204
Reputation: 5741
To create folder use createFolder method.
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);
}
}
Upvotes: 1