Copy a file with InputStream and OutputStream

The following code uses the InputStream and OutputStream to do the byte level file copy.


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class Main {
  final static int BUFF_SIZE = 5 * 1024 * 1024; // 5MB
  final static byte[] buffer = new byte[BUFF_SIZE];

  public static void main(String[] arg) throws IOException {
    copy(new File("s"), new File("t"));
  }
  public static void copy(File s, File t) throws IOException {
    InputStream in = new FileInputStream(s);
    FileOutputStream out = new FileOutputStream(t);
    while (true) {
      int count = in.read(buffer);
      if (count == -1)
        break;
      out.write(buffer, 0, count);
    }
    out.close();
    in.close();
  }
}
Home 
  Java Book 
    Runnable examples  

IO File:
  1. Compare File Dates
  2. Compress files using with ZIP
  3. Concatenate files
  4. Copy a File with NIO FileChannel and ByteBuffer
  5. Copy a file with FileReader and FileWriter
  6. Copy a file with InputStream and OutputStream
  7. Copy a file and overwrite
  8. Delete a file
  9. Delete File Recursively
  10. Get readable file size
  11. Move a file
  12. Rename a file
  13. Report a file's status
  14. Search a file by regular expressions
  15. Touch a file: set File Last Modified Time