Java在File尾部追加数据的两种方法
package cn.com;import java.io.FileWriter;import java.io.RandomAccessFile;//问题描述: //在文件的末尾追加内容//方法1:利用RandomAccessFile类//1将randomAccessFile模式设置为rw//2将randomAccessFile移动(seek)到文件末尾//3追加数据//4关闭流//方法2:利用FileWriter类//1将FileWriter构造方法第二个参数置为true.表示在尾部追加//2追加数据//3关闭流public class FileTest {public static void main(String[] args) {FileTest fileTest = new FileTest();fileTest.addContentFirst("F:\\temp.txt", "test1");fileTest.addContentSecond("F:\\temp.txt", "test2");}public void addContentFirst(String filePath, String newContent) {try {RandomAccessFile randomAccessFile=new RandomAccessFile(filePath, "rw");long fileLength=randomAccessFile.length();randomAccessFile.seek(fileLength);randomAccessFile.write(newContent.getBytes("UTF-8"));randomAccessFile.close();} catch (Exception e) {}}public void addContentSecond(String filePath, String newContent) { try {FileWriter fileWriter=new FileWriter(filePath, true);fileWriter.write(newContent);fileWriter.close();} catch (Exception e) {}}}