Results 1 to 5 of 5
Thread: Purpose of close() ?
- 01-12-2012, 09:50 PM #1
Senior Member
- Join Date
- Nov 2011
- Location
- Turkey
- Posts
- 378
- Blog Entries
- 24
- Rep Power
- 2
Purpose of close() ?
Hi.
My Code is:
So my question is:Java Code:public class TestClass { public static void main(String[] args) { PrintWriter outputStream = null; try { outputStream = new PrintWriter(new FileOutputStream("c:/stuff.txt")); } catch(FileNotFoundException e) { } System.out.println("Writing to file."); for(int i = 0;i<10000;i++) { outputStream.println(i); } //outputStream.close(); } }
How does JAVA decide on when to call .close?
When outputStream.close is commented out:
When I put i<100 for example, there are no values in my stuff.txt file.
When I put a larger number, such as 10000, I see some values in my stuff.txt file, up to ~8500 for example.
If I do not comment out close(), then whatever the number i is, I get correct amount of integers in my stuff.txt
Any ideas?
- 01-12-2012, 10:39 PM #2
Re: Purpose of close() ?
If you do not call close, data could be left in a buffer waiting for more data to fill the buffer before doing a write to disk.
Its best to close the file as soon as the writing or reading is done.
- 01-12-2012, 10:41 PM #3
Senior Member
- Join Date
- Nov 2011
- Location
- Turkey
- Posts
- 378
- Blog Entries
- 24
- Rep Power
- 2
Re: Purpose of close() ?
Thanks.
But how does it decide when to do that ?
And in a Book called Absolute Java (3rd Edition) it says close is always called automatically when program finishes. It doesn't look so true?
- 01-12-2012, 10:47 PM #4
Re: Purpose of close() ?
Its better if you do it, rather than hope the JVM will do it.
- 01-13-2012, 09:57 AM #5
Moderator
- Join Date
- Apr 2009
- Posts
- 10,448
- Rep Power
- 16
Re: Purpose of close() ?
close() calls flush() before closing the stream (in most stream cases).
flush() sends the contents of the buffer to wherever it is supposed to go (disk in your case).
And that book is wrong. There is no guarantee that a stream will close as a program exits.
You should do so explicitly, and in a finally block.
Similar Threads
-
Can't understand the purpose of interfaces
By Vortexnl in forum New To JavaReplies: 3Last Post: 02-13-2011, 05:10 PM -
Connecting two or more pcs for chating purpose
By Hussain Ali in forum NetworkingReplies: 2Last Post: 10-21-2010, 05:30 AM -
Will the connection.close() and statement.close() ever be called???
By Stephen Douglas in forum New To JavaReplies: 13Last Post: 04-09-2010, 11:15 AM -
Over-riding purpose fails..
By udayadas in forum New To JavaReplies: 7Last Post: 08-24-2008, 04:14 AM -
interface purpose?
By frejon26 in forum New To JavaReplies: 4Last Post: 01-24-2008, 03:39 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks