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