Breaking News
Home / Android / Android Snippets / Copy Bytes from InputStream to OutputStream – Android

Copy Bytes from InputStream to OutputStream – Android

Android File CopyWhen we want to copy data from one file to another, we can open an InputStream for the source file and OutputStream for the destination file, read chucks and perform data transfer.

In order to copy bytes over, we read the data from InputStream in chucks (say 1MB or any buffer size) and flush data to the Outputstream. The size of the buffer to choose really depends on the amount of memory available on the device , along with how fast we want the bytes to be copied over. Since the smart phone have significantly less memory than a desktop computer the buffer size needs to be kept less (optimal).

The following snippets shows how to copy bytes over from InputStream to OutputStream. <!>

  1. package com.livrona.andriod.commons.utils;
  2.  
  3. import java.io.BufferedInputStream;
  4. import java.io.BufferedOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.OutputStream;
  8.  
  9. public class IoUtils {
  10.         private static final int BUFFER_SIZE = 1024 * 2;
  11.  
  12.         private IoUtils() {
  13.                 // Utility class.
  14.         }
  15.  
  16.         public static int copy(InputStream input, OutputStream output) throws Exception, IOException {
  17.                 byte[] buffer = new byte[BUFFER_SIZE];
  18.  
  19.                 BufferedInputStream in = new BufferedInputStream(input, BUFFER_SIZE);
  20.                 BufferedOutputStream out = new BufferedOutputStream(output, BUFFER_SIZE);
  21.                 int count = 0, n = 0;
  22.                 try {
  23.                         while ((n = in.read(buffer, 0, BUFFER_SIZE)) != 1) {
  24.                                 out.write(buffer, 0, n);
  25.                                 count += n;
  26.                         }
  27.                         out.flush();
  28.                 } finally {
  29.                         try {
  30.                                 out.close();
  31.                         } catch (IOException e) {
  32.                                 Log.e(e.getMessage(), e);
  33.                         }
  34.                         try {
  35.                                 in.close();
  36.                         } catch (IOException e) {
  37.                                 Log.e(e.getMessage(), e);
  38.                         }
  39.                 }
  40.                 return count;
  41.         }
  42.  
  43. }
[pb_builder]

Check Also

How to check if an Android device can connect to Internet?

The following code snippet shows how to check if an Android device can connect to …

Advertisment ad adsense adlogger