Java 按行写入文件

在Java读写txt文件时,碰到要按行写入的问题,综合网上搜索出来的资料,似乎并没有专门的介绍。现将实习过程写下来,其实很简单。
关键是在声明FileWriter对象时要使用以下的构造函数,第二个参数@param:boolean append表示每次写文件时新内容附加在原来的内容后面,不而不是覆盖。

java.io.FileWriter.FileWriter(String fileName, boolean append) throws IOException

FileWriter
public FileWriter(String fileName,
boolean append)
throws IOException
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.

Parameters:
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the file rather than the beginning.
Throws:
IOException - if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason

实现的代码如下:

FileWriter fw = new FileWriter("e:\\ttp\\1.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("我爱java");
bw.newLine();
bw.flush(); //将数据更新至文件
bw.close();
fw.close();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值