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
1 2 3 4 5 |
String filepath = “abracadabra.xml”; File inputfile = new File(filepath); FileInputStream fileInput = new FileInputStream(inputfile); |
Input Stream Creation from File on a Server
1 2 3 4 5 6 7 8 9 |
URL url = new URL(dwnload_file_path); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod(“GET”); urlConnection.setDoOutput(true); urlConnection.connect(); //Stream used for reading the data from the internet InputStream inputStream = urlConnection.getInputStream(); //this is the total size of the file which we are downloading int totalSize = urlConnection.getContentLength(); |
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);
1 2 |
String FILENAME = “hello_file”; 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);
1 2 3 4 5 |
File SDCardRoot = Environment.getExternalStorageDirectory(); File file = new File(SDCardRoot,“downloaded_file.png”); 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 = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, readBytes);
}
Finally Close the output stream to write file to storage device.
fileOutput.close();
All Code
1 2 3 4 5 6 7 8 |
byte[] buffer = new byte[1024]; int readBytes = 0; while( (readBytes = inputStream.read(buffer)) > 0) { fileOutput.write(buffer, 0, readBytes); } fileOutput.close(); |
Catching Exceptions
Be Sure to put all above code inside a try/catch block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
try { //all code above } catch (final MalformedURLException e) { showError(“Error : MalformedURLException “ + e); e.printStackTrace(); } catch (final IOException e) { showError(“Error : IOException “ + e); e.printStackTrace(); } catch (final Exception e) { showError(“Error : Please check your internet connection “ + e); } |
Error Display Function for Above Try/Catch Block
1 2 3 4 5 6 7 |
void showError(final String err){ runOnUiThread(new Runnable() { public void run() { Toast.makeText(DownloadFileDemo1.this, err, Toast.LENGTH_LONG).show(); } }); } |