java - 如何使用缓冲写入器在文件中逐行写入?
问题描述
这是我在文件中逐行写入文本的代码
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缓冲区大小),而不是一次写一行?不确定我在这里缺少什么?
解决方案
您可以br.flush()
在每次调用后调用br.write(dataWithNewLine);
(在循环内)。
更简洁的替代方法是使用PrintWriter
with auto-flush:
PrintWriter pw = new PrintWriter(fr, true);
你可以用 写这个println
,就像用 一样System.out
,它每次都会刷新。
这也意味着您不必担心显式附加换行符。
推荐阅读
- c++ - 如何在 c++ builder 中动态声明 c# dll 函数
- node.js - Sequelize 和在关联中指定外键的问题
- jquery - toggleClass:删除当前类并添加一个新类
- postman - 邮递员:如何存储响应中的数组并使用它来发出多个请求
- python - 有没有办法在同一个 conda 环境中安装 python 3 和 python 2?
- data-structures - 非结构化数据方法和解决方案
- python - 如何让pocketsphinx识别关键词
- excel - 如果 K 列中的单元格返回 FALSE,则清除 B 列中的单元格
- java - 将 MySQL 数据库的默认日期选择器值设置为 NULL
- python - 用于替换不在引号之间的特定单词的正则表达式