English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Java

Contrôle de flux Java

Java Array

Java Orienté Objet (I)

Java Orienté Objet (II)

Java Orienté Objet (III)

Gestion des exceptions en Java

Java List

Java Queue (filet)

Java Map Collections

Java Set Collections

Java Entrée Sortie (I/O)/O)

Reader Java/Writer

Autres sujets Java

Programme Java pour copier un fichier

Java example大全

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.

Exemple : utiliser I / Copie de fichier avec flux O

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.

Java example大全