Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

PrintWriter - autoFlush  RSS feed

 
Mahesh Mamani
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
Would like to know the meaning of the autoFlush variable in the PrintWriter constructor.
I created a small program with autoFlush as false and the true, but both give me same output. Could any1 pls convey the meaning of this.
From the API:
PrintWriter(Writer out, boolean autoFlush)
Create a new PrintWriter.
autoFlush - A boolean; if true, the println() methods will flush the output buffer
Here's my pgm:
import java.io.*;
public class rajan
{
public static void main(String kk[]){
PrintWriter log = null;
String bsdDirectConnLog;
bsdDirectConnLog = "hello1.txt";
try {
log = new PrintWriter(new FileOutputStream(bsdDirectConnLog,true),true);
//cannot open the requested file.Open the default file.
} catch (IOException e1) {
System.out.println(e1.getMessage());
}
log.println("Using weblogic jdbc driver");
log.println("Using weblogic jdbc driver");
log.println("Using weblogic jdbc driver");
log.println("Using weblogic jdbc driver");
log.close();
//log.println("Log file =" + bsdDirectConnLog);
}
}
If we change the bsdDirectConn.log to hello2.txt and the autoFlush value in the PrintWriter constructor to false, both the files(hello1.txt and hello2.txt are identical).
Why is it so???
Thanks in advance.
Mahesh
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Autoflush only controls whether println() performs a flush for each line. The close() method also performs a flush, and this is not controlled by the autoflush. As long as the flush is performed once at the end, it doesn't really matter much whether or not it was called beforehand. (It might have mattered if you were looking at the file while the program was still running - but looking only at the final file, it doesn't matter.)
Incidentally, if you omit the close() statements you will probably still see the same results, as the streams will probably be flushed by the JVM before it exits. I'm not sure if this behavior is guaranteed, but it often seems to be the case.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!