【发布时间】:2018-06-27 16:10:09
【问题描述】:
这是我在文件中逐行写入文本的代码
public class TestBufferedWriter {
public static void main(String[] args) {
// below line will be coming from user and can vary in length. It's just an example
String data = "I will write this String to File in Java";
int noOfLines = 100000;
long startTime = System.currentTimeMillis();
writeUsingBufferedWriter(data, noOfLines);
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println(elapsedTime);
System.out.println("process end");
}
private static void writeUsingBufferedWriter(String data, int noOfLines) {
File file = new File("C:/testFile/BufferedWriter.txt");
FileWriter fr = null;
BufferedWriter br = null;
String dataWithNewLine=data+System.getProperty("line.separator");
try{
fr = new FileWriter(file);
br = new BufferedWriter(fr);
for(int i = 0; i<noOfLines; i++){
br.write(dataWithNewLine);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
br.close();
fr.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
但是它一次写入多行(使用 8192 缓冲区大小),而不是一次写入一行?不确定我在这里缺少什么?
【问题讨论】:
-
另外:使用 try-with-resources 而不是手动关闭流。
-
您能评论一下您认为 BufferedWriter 是什么意思吗?
标签: java file filewriter bufferedwriter