Search code examples
javafilefilewriterbufferedwriter

How to write line by line in file using buffered writer?


Here is my code to write the text in file line by line

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();
            }
        }
    }

}

But its writing multiple lines(using 8192 buffer size) in one go , instead of writing one line at a time ? Not sure what I am missing here ?


Solution

  • You could call br.flush() after every call to br.write(dataWithNewLine); (inside the loop).

    A more concise alternative would be to use a PrintWriter with auto-flush:

    PrintWriter pw = new PrintWriter(fr, true);
    

    You can write to this with println, just as with System.out, and it will flush every time.

    This also means you wouldn't have to worry about appending the newline character explicitly.