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

时间:2018-06-27 16:10:09

标签: 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缓冲区大小),而不是一次写入一行?不知道我在这里想念什么吗?

1 个答案:

答案 0 :(得分:1)

每次调用br.flush()之后(循环内),您都可以调用br.write(dataWithNewLine);

更简洁的选择是使用PrintWriter with auto-flush

PrintWriter pw = new PrintWriter(fr, true);

您可以使用println进行写操作,就像使用System.out一样,它每次都会刷新。

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