English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans ce tutoriel, nous allons apprendre à copier un fichier en utilisant Java.
Fichier JavaLa classe ne fournit aucune méthode pour copier un fichier dans un autre, mais nous pouvons utiliserJava I / Flux OLire le contenu d'un fichier et l'écrire dans un autre fichier.
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"); //Lire toutes les données à partir de input.txt sourceFile.read(array); //Écrire toutes les données dans newFile destFile.write(array); System.out.println("Copier le fichier input.txt vers newFile."); // Close the stream sourceFile.close(); destFile.close(); } catch (Exception e) { e.getStackTrace(); } } }
Output result
Copy the 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 the contents of the array to newFile
Attention points:
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.