Search code examples
javaoutputprintwriter

Why the method PrintWriter.print(string) doesn't stream text into the output file and waits to be closed before writing down the text?


I have the following code :

PrintWriter logput = new PrintWriter("path\\log.txt", "UTF-8");
for (String symb : symbolList) {
System.out.println(symb);
logput.println(symb);
}
logput.close();

The for loop runs for hours so I have to stop the program eventually. When I check the log.txt it is empty while System.out prints the symb value every iteration without problem. This means that println methods waits the close method call before effectivly writing text into the file.

This is very bad for me, is there any other way of writing text into file with java that doesn't have this problem ?

Edit : flush() method does the job, thank to the comments. Additionaly could one tell me how to prevent PrintWriter logput = new PrintWriter("path\\log.txt", "UTF-8"); from deleting pre-existing content in log.txt ?


Solution

  • How do I not overwrite the previous file

    If you use the OutputStream constructor instead of the File constructor, you can make your own instance of FileOutputStream which uses the constructor that tells the outputstream to append instead of overwrite. http://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html

    How do I autoflush?

    PrintWriter has a constructor that takes an extra boolean to set autoflush

    http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#PrintWriter%28java.io.OutputStream,%20boolean%29

    Putting these together:

    PrintWriter logput = new PrintWriter(new FileOutputStream("path\\log.txt", true),  true);
    for (String symb : symbolList) {
       System.out.println(symb);
       logput.println(symb);
     }
     logput.close();
    

    If you need to use UTF-8 charset you have to make your own OutputStreamWriter

    //boolean here is for append
    Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("path\\log.txt", true), "UTF-8"))
     //boolean here is for autoflush
     PrintWriter logput = new PrintWriter(writer,  true);
    for (String symb : symbolList) {
       System.out.println(symb);
       logput.println(symb);
     }
     logput.close();