问题描述:
在文件的末尾追加内容
方法1:利用RandomAccessFile类
1.将randomAccessFile模式设置为rw
2将randomAccessFile移动(seek)到文件末尾
3追加数据
4关闭流
方法2:利用FileWriter类
1.将FileWriter构造方法第二个参数置为true.表示在尾部追加
2追加数据
3.关闭流
实现代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
package cn.com; import java.io.FileWriter; import java.io.RandomAccessFile; 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) { } } } |
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:http://blog.csdn.net/lfdfhl/article/details/8302671