如何在 Java 中編寫一個程式從一個檔案複製字元到另一個檔案中?


按字元逐個字元複製一個檔案的內容到另一個檔案中

示例

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyFiles {
   public static void main(String[] args) throws IOException {
      //Creating a File object to hold the source file
      File source = new File("D:\ExampleDirectory\SampleFile.txt");
      //Creating a File object to hold the destination file
      File destination = new File("D:\ExampleDirectory\outputFile.txt");
      //Creating an FileInputStream object
      FileInputStream inputStream = new FileInputStream(source);
      //Creating an FileOutputStream object
      FileOutputStream outputStream = new FileOutputStream(destination);
      //Creating a buffer to hold the data
      int length = (int) source.length();
      byte[] buffer = new byte[length];
      while ((length = inputStream.read(buffer)) > 0) {
         outputStream.write(buffer, 0, length);
      }
      inputStream.close();
      outputStream.close();
      System.out.println("File copied successfully.......");
   }
}

輸出

File copied successfully.......

更新於: 02-Aug-2019

2K+ 瀏覽

開啟你的 職業生涯

完成該課程以獲得認證

開始學習
廣告