java写文件时往末尾追加文件(而不是覆盖原文件),的两种方法总结

代码如下:

  1. import java.io.FileWriter;
  2. import java.io.IOException;
  3. import java.io.RandomAccessFile;
  4. public class AppendToFile {
  5. /**
  6. * A方法追加文件:使用RandomAccessFile
  7. */
  8. public static void appendMethodA(String fileName, String content) {
  9. try {
  10. // 打开一个随机访问文件流,按读写方式
  11. RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
  12. // 文件长度,字节数
  13. long fileLength = randomFile.length();
  14. //将写文件指针移到文件尾。在该位置发生下一个读取或写入操作。
  15. randomFile.seek(fileLength);
  16. //按字节序列将该字符串写入该文件。
  17. randomFile.writeBytes(content);
  18. //关闭此随机访问文件流并释放与该流关联的所有系统资源。
  19. randomFile.close();
  20. } catch (IOException e) {
  21. e.printStackTrace();
  22. }
  23. }
  24. /**
  25. * B方法追加文件:使用FileWriter
  26. */
  27. public static void appendMethodB(String fileName, String content) {
  28. try {
  29. //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件,如果为 true,则将字节写入文件末尾处,而不是写入文件开始处
  30. FileWriter writer = new FileWriter(fileName, true);
  31. writer.write(content);
  32. writer.close();
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. public static void main(String[] args) {
  38. String fileName = "C:/Temp.txt";
  39. String content = "new append!";
  40. //按方法A追加文件
  41. AppendToFile.appendMethodA(fileName, content);
  42. AppendToFile.appendMethodA(fileName, "append end. ");
  43. //显示文件内容
  44. ReadFromFile.readFileByLines(fileName);
  45. //按方法B追加文件
  46. AppendToFile.appendMethodB(fileName, content);
  47. AppendToFile.appendMethodB(fileName, "append end. ");
  48. //显示文件内容
  49. ReadFromFile.readFileByLines(fileName);
  50. }
  51. }

java控制台输出结果如下:

  1. ++++++readFileByLines:++++++
  2. 以行为单位读取文件内容,一次读一整行:
  3. line 1: Sun Yat-sen(November 12, 1866–March 12, 1925) was a Chinese revolutionary and political leader who is often referred to as the "father of modern China". Sun played an instrumental and leadership role in the eventual overthrow of the Qing Dynasty in 1911. He was the first provisional president when the Republic of China was founded in 1912. He later co-founded the Kuomintang (KMT) where he served as its first leader. new append!append end.
  4. ++++++readFileByLines:++++++
  5. 以行为单位读取文件内容,一次读一整行:
  6. line 1: Sun Yat-sen(November 12, 1866–March 12, 1925) was a Chinese revolutionary and political leader who is often referred to as the "father of modern China". Sun played an instrumental and leadership role in the eventual overthrow of the Qing Dynasty in 1911. He was the first provisional president when the Republic of China was founded in 1912. He later co-founded the Kuomintang (KMT) where he served as its first leader. new append!append end.
  7. line 2: new append!append end.
原文地址:https://www.cnblogs.com/jpfss/p/9789296.html