Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Writing to a file



At 2:14 PM -0400 5/15/01, Jon Lucenius wrote:
Thanks so much for the help.

You'll want to fw.close() or fw.flush() the file. Otherwise the
output will be buffered until the object is finalized (most output
stream objects close themselves on finalization -- since you
obviously forgot). But since your application probably just
terminates immediately, it's most likely that none of your objects
are ever finalized, and thus your file is never closed.

That did the trick - I am sure the other sample sent in would work as
well. Now my question is which way is better of the following two
methodologies: (most code snipped for brevity)

1) ** USING BUFFERED WRITER - EXAMPLE FROM JAVA.SUN.COM FOR Java 1.2 **

File fileOut = new File("/space/users/swd/java/testFile.txt");
BufferedWriter out = new BufferedWriter(new FileWriter(fileOut));
out.write("we are writting to a file ");
out.close();

2) ** USE FILEWRITER AS I ORIGINALLY POSTED WITH HELP FROM ABOVE **

File fileOut = new File("/space/users/swd/java/testFile.txt");
FileWriter fw = new FileWriter(fileOut);
fw.write("docHeader\n");
fw.close();

IOW should I use the BufferedWriter wrapper or not?

As a general rule, I use a BufferedWriter (or BufferedReader) whenever I'm going to call the write routine more than a 5 or 10 times before closing the file.

The difference is that BufferedWriter allocates a buffer (duh!) and all of the write() methods just copy chars into the buffer until it fills up. Then, the buffer is dumped to the FileWriter in a single write().

In contrast, the FileWriter passes each write() call directly to the operating system, with all the attendant API overhead. This is great if you need granular control over writes (say you're writing to an inter-process pipe or an IP port or something). Or, if you are writing huge chunks of data at once. But mostly it just adds a lot of overhead.

For really, really, small files you'll never notice the difference -- and you might want to avoid the additional memory requirements of BufferedWriter.

For for just about everything else, BufferedWriter is *much* more efficient. I've got a text parser program that I sped up by an order of magnitude simply by wrapping a BufferedWriter/BufferedReader around each FileWriter or FileReader. I'm not kidding. My run times went from about 20 seconds to 3 (I thought I'd broken something).

James

__________________________________
James Bucanek
<mailto:email@hidden>


References: 
 >Re: Writing to a file (From: Jon Lucenius <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.