如下所示:
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); }}以上這篇java在文件尾部追加內容的簡單實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。