在 Java 中使用 FileStreams 複製檔案\n


本示例展示瞭如何使用 FileStreams 類的讀寫方法將一個檔案的內容複製到另一個檔案中。

示例

動態演示

import java.io.*;

public class Main {
   public static void main(String[] args) throws Exception {
      BufferedWriter out1 = new BufferedWriter(new FileWriter("srcfile"));
      out1.write("string to be copied
");       out1.close();       InputStream in = new FileInputStream(new File("srcfile"));       OutputStream out = new FileOutputStream(new File("destnfile"));       byte[] buf = new byte[1024];       int len;       while ((len = in.read(buf)) > 0) {          out.write(buf, 0, len);       }       in.close();       out.close();       BufferedReader in1 = new BufferedReader(new FileReader("destnfile"));       String str;       while ((str = in1.readLine()) != null) {          System.out.println(str);       }       in.close();    } }

結果

上述程式碼示例會產生以下結果。

string to be copied

以下是另一個簡單的示例,展示瞭如何在 Java 中將一個檔案複製到另一個檔案中

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class CopyExample {
   public static void main(String[] args) {
      FileInputStream ins = null;
      FileOutputStream outs = null;
      try {
         File infile =new File("C:\Users\TutorialsPoint7\Desktop\abc.txt");
         File outfile =new File("C:\Users\TutorialsPoint7\Desktop\bbc.txt");
         ins = new FileInputStream(infile);
         outs = new FileOutputStream(outfile);
         byte[] buffer = new byte[1024];
         int length;

         while ((length = ins.read(buffer)) > 0) {
            outs.write(buffer, 0, length);
         }          
         ins.close();
         outs.close();
         System.out.println("File copied successfully!!");
      } catch(IOException ioe) {
         ioe.printStackTrace();
      }    
   }
}

上述程式碼示例會產生以下結果。

File copied successfully!!

更新時間: 2020 年 6 月 18 日

265 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始使用
廣告
© . All rights reserved.