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) {
}
}
}