案例

读取文件

  1. import java.io.*;
  2. public class Main {
  3. public static void main(String[] args) throws Exception {
  4. String path = "./story.txt";
  5. boolean append = true;
  6. BufferedWriter bw = new BufferedWriter(new FileWriter(path, append));
  7. bw.write("123\n");
  8. bw.write(97);
  9. bw.newLine();
  10. bw.write(new char[]{'G', 'G', 'C', '\n'});
  11. bw.write("123\n56789", 0, 9);
  12. bw.write(new char[]{'G', 'G', 'C', 'S', '\n'}, 0, 5);
  13. bw.close();
  14. }
  15. }

复制文件

一边读一边写

  1. import java.io.*;
  2. public class Main {
  3. public static void main(String[] args) throws Exception {
  4. String srcPath = "./story.txt";
  5. String copypath = "./story_copy.txt";
  6. boolean append = false;
  7. BufferedReader br = new BufferedReader(new FileReader(srcPath));
  8. BufferedWriter bw = new BufferedWriter(new FileWriter(copypath, append));
  9. String line;
  10. while ((line = br.readLine()) != null) {
  11. bw.write(line);
  12. bw.newLine();
  13. }
  14. br.close();
  15. bw.close();
  16. }
  17. }