File copy

In this chapter you will learn:

  1. How to use FileInputStream and FileOutputStream to copy a file

Use FileInputStream and FileOutputStream to copy a file

The following code use FileInputStream and FileOutputStream to copy a file. It creates FileInputStream from source file path and creates FileOutputStream for target file path. Then it reads the source file byte by byte and writes to the target file.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/* j a  v a  2 s  .c  o m*/
public class Main {

  public static void main(String[] args) throws Exception {

    FileInputStream fin = null;
    FileOutputStream fout = null;

    File file = new File("C:/myfile1.txt");

    fin = new FileInputStream(file);
    fout = new FileOutputStream("C:/myfile2.txt");

    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = fin.read(buffer)) > 0) {
      fout.write(buffer, 0, bytesRead);
    }
    fin.close();
    fout.close();
  }
}

The close() methods for both input and output streams are important. Remember to close them.

Next chapter...

What you will learn in the next chapter:

  1. Stream vs Reader and writer
  2. Get to know InputStream
  3. Get to know OutputStream
  4. Get to know Reader
  5. Get to know Writer