Java 实例 - 将文件内容复制到另一个文件

以下实例演示了使用 BufferedWriter 类的 read 和 write 方法将文件内容复制到另一个文件:

Main.java 文件

  1. import java.io.*;
  2. public class Main {
  3. public static void main(String[] args) throws Exception {
  4. BufferedWriter out1 = new BufferedWriter(new FileWriter("srcfile"));
  5. out1.write("string to be copied\n");
  6. out1.close();
  7. InputStream in = new FileInputStream(new File("srcfile"));
  8. OutputStream out = new FileOutputStream
  9. (new File("destnfile"));
  10. byte[] buf = new byte[1024];
  11. int len;
  12. while ((len = in.read(buf)) > 0) {
  13. out.write(buf, 0, len);
  14. }
  15. in.close();
  16. out.close();
  17. BufferedReader in1 = new BufferedReader(new FileReader("destnfile"));
  18. String str;
  19. while ((str = in1.readLine()) != null) {
  20. System.out.println(str);
  21. }
  22. in1.close();
  23. }
  24. }

以上代码运行输出结果为:

  1. string to be copied