码迷,mamicode.com
首页 > 编程语言 > 详细

java追加写入txt文件

时间:2017-12-08 01:23:51      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:write   string   except   整理   long   ring   写入   ati   oid   

整理了下网上的资料,数据追加写入txt文件有三种方式,见下面代码:

方法一:

 1 public void method1() {
 2 FileWriter fw = null;
 3 try {
 4 //如果文件存在,则追加内容;如果文件不存在,则创建文件
 5 File f=new File("E:\\dd.txt");
 6 fw = new FileWriter(f, true);
 7 } catch (IOException e) {
 8 e.printStackTrace();
 9 }
10 PrintWriter pw = new PrintWriter(fw);
11 pw.println("追加内容");
12 pw.flush();
13 try {
14 fw.flush();
15 pw.close();
16 fw.close();
17 } catch (IOException e) {
18 e.printStackTrace();
19 }
20 }

方法二:

 1 public static void method2(String file, String conent) {
 2 BufferedWriter out = null;
 3 try {
 4 out = new BufferedWriter(new OutputStreamWriter(
 5 new FileOutputStream(file, true)));
 6 out.write(conent+"\r\n");
 7 } catch (Exception e) {
 8 e.printStackTrace();
 9 } finally {
10 try {
11 out.close();
12 } catch (IOException e) {
13 e.printStackTrace();
14 }
15 }
16 }

方法三:

 1 public static void method3(String fileName, String content) {
 2 try {
 3 // 打开一个随机访问文件流,按读写方式
 4 RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
 5 // 文件长度,字节数
 6 long fileLength = randomFile.length();
 7 // 将写文件指针移到文件尾。
 8 randomFile.seek(fileLength);
 9 randomFile.writeBytes(content+"\r\n");
10 randomFile.close();
11 } catch (IOException e) {
12 e.printStackTrace();
13 }
14 }
15 }

 

java追加写入txt文件

标签:write   string   except   整理   long   ring   写入   ati   oid   

原文地址:http://www.cnblogs.com/wdpnodecodes/p/8001557.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!