Skip to content

How to Copy File in Java

Ramesh Fadatare edited this page Jul 17, 2018 · 2 revisions

Overview

Java didn’t comes with any ready make file copy function, you have to manual create the file copy process. To copy file, just convert the file into a bytes stream with FileInputStream and write the bytes into another file with FileOutputStream.

Copy File Example Here’s an example to copy a file named “sample1.txt” to another file named “sample2.txt”. If the file “sample2.txt” is exists, the existing content will be replace, else it will create with the content of the “sample1.txt”.

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;

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());
		}
	}
}

Reference

https://docs.oracle.com/javase/8/docs/api/java/io/FileInputStream.html https://docs.oracle.com/javase/8/docs/api/java/io/FileOutputStream.html

Clone this wiki locally