English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive List of Java Examples
In this tutorial, we will learn how to copy files using Java.
Java fileThe class does not provide any method to copy a file to another file. But we can useJava I / StreamRead content from one file and write it to another file.
import java.io.FileInputStream; import java.io.FileOutputStream; class Main { public static void main(String[] args) { byte[] array = new byte[50]; try { FileInputStream sourceFile = new FileInputStream("input.txt"); FileOutputStream destFile = new FileOutputStream("newFile"); //Read all data from input.txt sourceFile.read(array); //Write all data to newFile destFile.write(array); System.out.println("Copy the input.txt file to newFile."); // Close the streams sourceFile.close(); destFile.close(); } catch (Exception e) { e.getStackTrace(); } } }
Output Results
Copy input.txt file to newFile.
In the above example, we use FileInputStream and FileOutputStream to copy one file to another.
Here,
FileInputStream frominput.txtRead all contents into an array
FileOutputStream writes all contents of the array to newFile
Cautionary Notes:
The org.apache.commons.io package's FileUtils class provides a copyFile() method to copy files.
The java.nio package's Files class provides a copy() method to copy files.