Copy File in Java

Description

The following code shows how to copy File.

Example


//w w w  .ja  v  a 2s.co  m
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {

  public static void main(String[] args) {

    if (args.length != 2) {
      System.err.println("Usage: java Main infile outfile");
    }
    try {
      copy(args[0], args[1]);
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }

  public static void copy(String inFile, String outFile) throws IOException {

    FileInputStream fin = null;
    FileOutputStream fout = null;

    try {
      fin = new FileInputStream(inFile);
      fout = new FileOutputStream(outFile);
      copy(fin, fout);
    } finally {
      try {
        if (fin != null)
          fin.close();
      } catch (IOException ex) {
      }
      try {
        if (fout != null)
          fout.close();
      } catch (IOException ex) {
      }
    }
  }

  public static void copy(InputStream in, OutputStream out) throws IOException {

    byte[] buffer = new byte[1024];
    while (true) {
      int bytesRead = in.read(buffer);
      if (bytesRead == -1)
        break;
      out.write(buffer, 0, bytesRead);
    }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip