import java.io.FileWriter;import java.io.IOException;import java.io.RandomAccessFile;/** * 將內容追加到檔案尾部. * @author haicheng.cao * */public class AppendToFile { /** * A方法追加檔案:使用RandomAccessFile */ public static void appendMethodA(String fileName, String content) { try { // 開啟一個隨機訪問檔案流,按讀寫方式 RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw"); // 檔案長度,位元組數 long fileLength = randomFile.length(); //將寫檔案指標移到檔案尾。 randomFile.seek(fileLength); randomFile.writeBytes(content); randomFile.close(); } catch (IOException e) { e.printStackTrace(); } } /** * B方法追加檔案:使用FileWriter */ public static void appendMethodB(String fileName, String content) { try { //開啟一個寫檔案器,建構函式中的第二個參數true表示以追加形式寫檔案 FileWriter writer = new FileWriter(fileName, true); writer.write(content); writer.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { String fileName = "C:/temp/newTemp.txt"; String content = "new append!"; //按方法A追加檔案 AppendToFile.appendMethodA(fileName, content); AppendToFile.appendMethodA(fileName, "append end. \n"); //顯示檔案內容 ReadFromFile.readFileByLines(fileName); //按方法B追加檔案 AppendToFile.appendMethodB(fileName, content); AppendToFile.appendMethodB(fileName, "append end. \n"); //顯示檔案內容 ReadFromFile.readFileByLines(fileName); }}