Java – about the close method used to close the flow ()
Today, when I'm working on some kind of servlet, I'm using the following code to perform a write operation. These servlets are writing some information to a file on my hard disk
File f=new File("c:/users/dell/desktop/ja/MyLOgs.txt"); PrintWriter out=new PrintWriter(new FileWriter(f,true)); out.println("the name of the user is "+name+"\n"); out.println("the email of the user is "+ email+"\n"); out.close(); //**my question is about this statement**
When I don't use this statement, the servlet compiles well, but it doesn't write any files, but when I include it, the write operation is successful My question is:
>Why didn't I write the data to the file when I didn't include the statement (even if my servlet compiled without any errors)? > To what extent is the closure of the stream considerable?
Solution
Calling close () causes all data to be refreshed You built a printwriter without enabling automatic refresh (the second parameter of one of the constructors), which means you have to manually call flush(), and close() will do it for you
Closing also frees up any system resources used to open the file Although the VM and the operating system will eventually close the file, it is best to close it after completion to save memory on the computer
You can also put close () in a finally block to ensure that it is always called For example:
PrintWriter out = null; try { File f = new File("c:/users/dell/desktop/ja/MyLOgs.txt"); out = new PrintWriter(new FileWriter(f,true)); out.println("the name of the user is "+name+"\n"); out.println("the email of the user is "+ email+"\n"); } finally { out.close(); }
See: printwriter
Sanchit also puts forward a good idea that Java 7 VM can automatically close streams when you don't need them