java - 如何使用缓冲写入器在文件中逐行写入?

标签 java file filewriter bufferedwriter

这是我的代码,用于将文本逐行写入文件

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.write(dataWithNewLine); (在循环内)之后调用 br.flush()

更简洁的替代方案是使用 PrintWriter with auto-flush :

PrintWriter pw = new PrintWriter(fr, true);

您可以使用 println 写入此内容,就像使用 System.out 一样,它每次都会刷新。

这也意味着您不必担心显式附加换行符。

关于java - 如何使用缓冲写入器在文件中逐行写入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51067241/

相关文章:

java - Java 枚举中的递归?

C正在将字符串转换为十六进制

java - 写入时移动文件?

java - Java 中的斐波那契数列使用动态编程和递归

java - Akka-Java 路由问题

java - 为什么java中无法提取Json数组?

java - org.hibernate.HibernateException : Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

c# - 如何从 C# 中的 URL 下载文件?

Java nio2 目录没有关闭。导致 "too many open files"错误

java - 将多行 JTextArea 内容写入文件