Java FileOutputStream copy file

Introduction

The following example uses write() from FileOutputStream to copy a file:

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

public class Main {
  public static void main(String args[]) throws IOException {
    int i;// ww w. j  a  v  a  2s. com

    // Copy a File.
    try (FileInputStream fin = new FileInputStream("Main.java");
        FileOutputStream fout = new FileOutputStream("test.java");) {

      do {
        i = fin.read();
        if (i != -1)
          fout.write(i);
      } while (i != -1);
      fin.close();
      fout.close();

    } catch (IOException e) {
      System.out.println("I/O Error: " + e);
    }
  }
}



PreviousNext

Related