Java 實(shí)例 - 將文件內(nèi)容復(fù)制到另一個(gè)文件

Java 實(shí)例 Java 實(shí)例

以下實(shí)例演示了使用 BufferedWriter 類的 read 和 write 方法將文件內(nèi)容復(fù)制到另一個(gè)文件:

/*
 author by w3cschool.cn
 Main.java
 */

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\n");
      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);
      }
      in1.close();
   }
}

以上代碼運(yùn)行輸出結(jié)果為:

string to be copied

Java 實(shí)例 Java 實(shí)例