File Copy in Android


Copying Files in Android is all about creating Input Stream and Output Stream and then writing output stream with data from Input Stream.

Input Stream Creation for File on Device

Input Stream Creation from File on a Server

Output Stream Creation for Saving File on Internal Memory of Device

File will be written into the raw folder of your application and will be private to your app. No other app or user can see the file except your app.

First set String for name of your file.

String FILENAME = “hello_file”;

Create output file stream using Private Mode. Other modes are depricated.

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);

Output Stream Creation for Saving File on Root of External Storage i.e. SD Card

First get the Path of SD Card Root Folder.

File SDCardRoot = Environment.getExternalStorageDirectory();

Then create a new File Object with decided file name.

File file = new File(SDCardRoot,”downloaded_file.png”);

Finally Crate the Output Stream.

FileOutputStream fileOutput = new FileOutputStream(file);

Copy Internet Input Stream to Local Output Stream

First create a temporary buffer to store data from internet input stream.

byte[] buffer = new byte[1024];

Create an integer variable to store actual number of bytes read from internet input stream into this buffer. Set it initially to Zero. This will help to check if last byte is read from internet input stream.

int readBytes = 0;

Following while loop will keep on reading 1024 bytes at a time from internet input stream to buffer and then to local output stream until actual number of bytes read into the buffer i.e. bufferlength becomes zero.

while( (readBytes = > 0) {
fileOutput.write(buffer, 0, readBytes);
Finally Close the output stream to write file to storage device.


All Code

Catching Exceptions

Be Sure to put all above code inside a try/catch block.


Error Display Function for Above Try/Catch Block