如何在Java中讀取一個檔案的資料並列印到另一個檔案中?


Java提供I/O流來讀取和寫入資料,其中流代表輸入源或輸出目標,可以是檔案、I/O裝置、其他程式等。

一般來說,流可以是輸入流或輸出流。

  • InputStream − 用於從源讀取資料。

  • OutputStream − 用於將資料寫入目標。

根據它們處理的資料,流有兩種型別:

  • 位元組流 − 這些流以位元組(8位)處理資料,即位元組流類讀取/寫入8位資料。使用這些流,您可以儲存字元、影片、音訊、影像等。

  • 字元流 − 這些流以16位Unicode處理資料。使用這些流,您只能讀取和寫入文字資料。

下圖說明了Java中所有輸入和輸出流(類)。

其中,您可以使用Scanner、BufferedReader和FileReader類讀取檔案內容。

同樣,您可以使用BufferedWriter、FileOutputStream、FileWriter將資料寫入檔案。

將一個檔案的內容寫入另一個檔案

以下是一個Java程式,它使用Scanner類將檔案資料讀取到字串中,並使用FileWriter類將其寫入另一個檔案中。

示例

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class CopyContent {
   public static void main(String[] args) throws IOException {
      //Instantiating a file class
      File file = new File("D:\sampleData.txt");
      //Instantiate an FileInputStream class
      FileInputStream inputStream = new FileInputStream(file);
      //Instantiating the Scanner class
      Scanner sc = new Scanner(inputStream);
      //StringBuffer to store the contents
      StringBuffer buffer = new StringBuffer();
      //Appending each line to the buffer
      while(sc.hasNext()) {
         buffer.append(" "+sc.nextLine());
      }
      System.out.println("Contents of the file: "+buffer);
      //Creating a File object to hold the destination file
      File dest = new File("D:\outputFile.txt");
      //Instantiating an FileWriter object
      FileWriter writer = new FileWriter(dest);
      //Writing content to the destination
      writer.write(buffer.toString());
      writer.flush();
      System.out.println("File copied successfully.......");
   }
}

輸出

Contents of the file: Tutorials Point originated from the idea that there exists a 
class of readers who respond better to online content and prefer to learn new skills 
at their own pace from the comforts of their drawing rooms. The journey commenced 
with a single tutorial on HTML in 2006 and elated by the response it generated, 
we worked our way to adding fresh tutorials to our repository which now proudly 
flaunts a wealth of tutorials and allied articles on topics ranging from programming 
languages to web designing to academics and much more. 40 million readers read 100 
million pages every month. Our content and resources are freely available and we prefer 
to keep it that way to encourage our readers acquire as many skills as they would like to. 
We don’t force our readers to sign up with us or submit their details either. 
No preconditions and no impediments. Simply Easy Learning!
File copied successfully.......

更新於:2019年9月10日

3K+ 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.