When 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. <!--break-->
- packagecom.livrona.andriod.commons.utils;
- importjava.io.BufferedInputStream;
- importjava.io.BufferedOutputStream;
- importjava.io.IOException;
- importjava.io.InputStream;
- importjava.io.OutputStream;
- publicclass IoUtils {
- privatestaticfinalint BUFFER_SIZE =1024*2;
- private IoUtils(){
- // Utility class.
- }
- publicstaticint copy(InputStream input, OutputStream output)throwsException, IOException{
- byte[] buffer =newbyte[BUFFER_SIZE];
- BufferedInputStream in =newBufferedInputStream(input, BUFFER_SIZE);
- BufferedOutputStream out =newBufferedOutputStream(output, BUFFER_SIZE);
- int count =0, n =0;
- try{
- while((n = in.read(buffer, 0, BUFFER_SIZE))!=-1){
- out.write(buffer, 0, n);
- count += n;
- }
- out.flush();
- }finally{
- try{
- out.close();
- }catch(IOException e){
- Log.e(e.getMessage(), e);
- }
- try{
- in.close();
- }catch(IOException e){
- Log.e(e.getMessage(), e);
- }
- }
- return count;
- }
- }