java 在file的尾部添加数据的两种方法总结
java在file的尾部添加数据的两种方法总结
问题描述:
在文件的末尾追加内容
方法1:利用RandomAccessFile类
1.将randomAccessFile模式设置为rw
2将randomAccessFile移动(seek)到文件末尾
3追加数据
4关闭流
方法2:利用FileWriter类
1.将FileWriter构造方法第二个参数置为true.表示在尾部追加
2追加数据
3.关闭流
实现代码:
packagecn.com;
importjava.io.FileWriter;
importjava.io.RandomAccessFile;
publicclassFileTest{
publicstaticvoidmain(String[]args){
FileTestfileTest=newFileTest();
fileTest.addContentFirst("F:\\temp.txt","test1");
fileTest.addContentSecond("F:\\temp.txt","test2");
}
publicvoidaddContentFirst(StringfilePath,StringnewContent){
try{
RandomAccessFilerandomAccessFile=newRandomAccessFile(filePath,"rw");
longfileLength=randomAccessFile.length();
randomAccessFile.seek(fileLength);
randomAccessFile.write(newContent.getBytes("UTF-8"));
randomAccessFile.close();
}catch(Exceptione){
}
}
publicvoidaddContentSecond(StringfilePath,StringnewContent){
try{
FileWriterfileWriter=newFileWriter(filePath,true);
fileWriter.write(newContent);
fileWriter.close();
}catch(Exceptione){
}
}
}
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!