Writing to files

posted by: Ms. Martin 7 February 2010 No Comment

As I mentioned really briefly, System.out is an object of type PrintStream. Check out the Java documentation to convince yourself that all PrintStream objects have print and println methods.

In order to print out to a file instead of to the console, all we have to do is have a PrintStream object that connects to a file. If you look carefully at the constructor list, you’ll see that there’s one that takes a file as a parameter. Bingo.

So here’s what you do. You build a File object using the filename you desire. Then you build a PrintStream object on that. You can do those two steps in one line or two — whichever makes most sense to you. For example:

File outputFile = new File("name here");
PrintStream out = new PrintStream(outputFile);

Note that if there doesn’t currently exist a file of the given name, it will be created for you. In case that can’t happen for some reason, creating the PrintStream object could throw a FileNotFoundException. You will need to deal with that appropriately.

In programs that create a bunch of output, it’s generally good style to have all the output done in one method. A good thing to do to give your program flexibility is to give this method a parameter of type PrintStream. That way you can print to a file or to System.out just by changing one parameter. That’s the beauty of parameterization!

1 Star2 Stars3 Stars4 Stars5 Stars (25 votes, average: 2.92 out of 5)
Loading ... Loading ...

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>