On Nov 17, 10:12*am, Matt <mgregor...@gmail.com> wrote:
> Can somebody explain to me why file output doesn't work unless the
> file is closed explicitly?
>
try
> {
> * * * * PrintWriter pw = new PrintWriter(new File("test.txt"));
> * * * * pw.print("Hello world!");
pw.flush();
> * * * * pw.close(); *// necessary?
>
> }
catch (...)
finally ...
> Shouldn't files be closed by the OS when the program ends? *
Of course files are 'closed' when the Java program
that had them loaded, has exited. No program has
them open, so they are closed.
>...If so, why
> doesn't the file ever get written?
>
> I tried making my own class which closes the file in finalize(), but
> that doesn't necessarily get called either, so that's out. *There's no
> other destructor type of thing in Java.
>
> I just don't understand why Java can't close the file for me. *All
> other languages do it and this is supposed to be a high level
> language. *It actually acts like the file was never opened for writing
> at all. *It might truncate the file to 0 bytes, but it never writes
> data to the file unless you manually close it. *Can anyone explain why
> the behavior is like this?
Java was designed for robustness, extensibility
and performance, rather than lazy programmers?
--
Andrew Thompson
http://pscode.org/