Writing to files for output

posted by: Mr. Bergquist 2 February 2014 No Comment

See if you can figure out printing to a file by reading resources, not relying on your teacher to explain every detail.  I suggest you use these:

  • Nice details description of how these all fit together in our Building Java Programs text, Section 6.4 Advanced File Processing, page 401 – 409.
  • Use the Java 7 API (Applications Programming Interface) – objects & their methods in the standard Java Libraries; this is what one uses to expand their programming skills.  Like a technical dictionary for Java.
  • 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.  Can you use printf() with a PrintStream??

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.

Important Note: 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!

Note: Updated from original version my Ms. Martin.  As always thanks!!

1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 4.25 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>