[an error occurred while processing this directive] CSE 142 Lab Resources: PrintStream

University of Washington, CSE 142

Lab Resources: PrintStream

Except where otherwise noted, the contents of this document are Copyright 2013 Stuart Reges and Marty Stepp.

lab document created by Marty Stepp, Stuart Reges and Whitaker Brand

Basic lab instructions

PrintStream

PrintStreams allow us to print to locations other than the console.
// to use the PrintStream
import java.io.*;
     ...

PrintStream printstreamName = new PrintStream(new File("outputFileName"));

Creating a PrintStream by giving it a File constructed with the parameter outputFileName:

PrintStream

Using a PrintStream is just like printing to the console! Just replace System.out with printstreamName.
printstreamName.print()
printstreamName.println();
printstreamName.printf();

Exercise : Printing with PrintStream

Consider the following code:
PrintStream out = new PrintStream(new File("output.txt"));
out.println("Jello world!");
For each of the following locations, write the expected output (or nothing, if we expect nothing to be printed):
output.txt:
Jello world!
console:  
nothing

Overwriting with PrintStream

Type in the entire contents of output.txt after each line of code has executed. If the file is blank, type nothing:
public static void main(String[] args) {
    PrintStream out = new PrintStream(new File("output.txt")); //nothing
    out.print("hey! ");                                        //hey! 
    out.println("hey! you! you!");                             //hey! hey! you! you!
    PrintStream out2 = new PrintStream(new File("output.txt"));//nothing
    out2.println("me");                                        //me 
}
This tells us that we should only make new PrintStreams when we want to overwrite the contents of a file/when we want to make a new file!