How to Copy File in Java

1. Overview

Java didn’t come with any ready make file copy function, you have to manually create the file copy process. To copy a file, just convert the file into a bytes stream with FileInputStream and write the bytes into another file with FileOutputStream.
Here’s an example to copy a file named “sample1.txt” to another file named “sample2.txt”. If the file “sample2.txt” exists, the existing content will be replaced, else it will create with the content of the “sample1.txt”.

2. Copy File Example

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This Java program demonstrates how to copy a file in java.
 * @author javaguides.net
 */

public class CopyFileExample {
 private static final Logger LOGGER = LoggerFactory.getLogger(CopyFileExample.class);

 public static void main(String[] args) {
  copyFile();
 }

 public static void copyFile() {
  try (InputStream inStream = new FileInputStream("sample1.txt");
    OutputStream outStream = new FileOutputStream("sample2.txt")) {
   byte[] buffer = new byte[1024];
   int length;
   // copy the file content in bytes
   while ((length = inStream.read(buffer)) > 0) {
    outStream.write(buffer, 0, length);
   }
  } catch (IOException e1) {
   LOGGER.error(e1.getMessage());
  }
 }
}

3. Reference

Comments