Writing to files
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
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!