Copy file from assets folder to external cache

 Suppose you have a file IsolationWardGuidelines.pdf in assets folder of your project and you want to copy it to external cache directory in order to read it.

 In order to copy the file in assets folder in onCreate event or any desired event, use the code given below.

java.io.File file = new java.io.File(getExternalCacheDir(), "IsolationWardGuidelines.pdf");
if (!file.exists()){
try{
java.io.InputStream asset = getAssets().open("IsolationWardGuidelines.pdf");
java.io.FileOutputStream output = new java.io.FileOutputStream(file);
final byte[] buffer = new byte[1024];
int size;
while ((size = asset.read(buffer)) != -1) {
output.write(buffer, 0, size);
}
asset.close();
output.close();
} catch (java.io.IOException e){
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}

Similar code can be use to copy a file from one file path to another file path. Following code copies a.pdf in /sdcard/11/ folder to /sdcard/Download/ folder.

java.io.File sourcefile = new java.io.File(Environment.getExternalStorageDirectory(), "/11/a.pdf");
java.io.File destfile = new java.io.File(Environment.getExternalStorageDirectory(), "/Download/a.pdf");
if (!destfile.exists()){
try{
java.io.InputStream instream = new java.io.FileInputStream(sourcefile);
java.io.FileOutputStream output = new java.io.FileOutputStream(destfile);
final byte[] buffer = new byte[1024];
int size;
while ((size = instream.read(buffer)) != -1){
output.write(buffer, 0, size);
}
instream.close();
output.close();
} catch (java.io.IOException e){
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}

Leave a Reply