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. \n");
  43. //顯示文件內容
  44. ReadFromFile.readFileByLines(fileName);
  45. //按方法B追加文件
  46. AppendToFile.appendMethodB(fileName, content);
  47. AppendToFile.appendMethodB(fileName, "append end. \n");
  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.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM