Simple Output to the Screen in a Console Window

The simplest possible way to get a Java program to display something on the "standard output" (the screen in your console window) is to use one or more of the statements illustrated below:

System.out.println(...stuff...); // Prints and outputs newline
System.out.print(...stuff...);   // Prints but does not output newline
System.out.println();            // Just outputs newline

The "stuff" that you put within the parentheses to be printed can be a literal value of a primitive type, a literal string, a variable, an arithmetic or other expression, an object reference, or several of these joined by plus signs.

Streams

Much input and output in Java takes place via streams. The term stream refers to a sequence of values from any input source of data (keyboard, file, port, and so on), or to any output destination for data (screen, file, port, and so on). The actual physical source or destination must be supplied as an argument to an appropriate constructor of an appropriate class, during the construction of the actual object that will do the physical reading or writing of data.

For example, to read bytes from a file or the keyboard into your program, you first need an "input stream". Then, to convert those bytes into characters appropriate for your particular operating system, you create an "input stream reader", as shown in the following diagram:

input stream (keyboard or file, for example)
 |
 | bytes
 v
input stream reader
 |
 | characters
 v
your program

And here is the analogous diagram for output:

your program
 |
 | characters
 v
output stream writer
 |
 | bytes
 v
output stream (screen or file, for example)

Console Input/Output

System.in is the system's name for the standard input stream object (your keyboard), which is automatically "opened" (or "set up for input") as an input stream when your program starts.

A "keyboard object" for reading from the console keyboard can therefore be instantiated as follows:

InputStreamReader inStream = new InputStreamReader(System.in);
BufferedReader keyboard = new BufferedReader(inStream);

Or, we could eliminate the intermediate variable inStream and do this in one step like this:

BufferedReader keyboard =
    new BufferedReader(new InputStreamReader(System.in));

Similarly, System.out is the system's name for the standard output stream object (your screen), which is automatically "opened" (or "set up for output") as an output stream when your program starts.

So, a "screen object" for writing to the screen display can therefore be instantiated as follows:

OutputStreamWriter outStream = new OutputStreamWriter(System.out);
PrintWriter screen = new PrintWriter(outStream, true);

Or, in a manner analogous to what we did above with input, we could eliminate the intermediate variable outStream and do this in one step like this:


PrintWriter screen =
    new PrintWriter(new OutputStreamWriter(System.out), true);

And, in fact, because the PrintWriter class has another constructor, whose analogue does not appear in the BufferedReader class, we can make the one-step version even simpler, like this:

PrintWriter screen = new PrintWriter(System.out, true);

Note that the second parameter to the PrintWriter constructor, which is given a value of true above, is optional. Its purpose is to cause automatic "flushing" of the output stream, so that everthing output by the program actually appears at the destination. Without this parameter we would need the following additional statement:

screen.flush();

Once we have the keyboard and screen objects, we can use them as illustrated below.

String name = keyboard.readLine();
screen.println("Hello, " + line);

Note that input is read as a String object, not including the newline character, and if numerical input is required it must be extracted from the input string.

File Input/Output

For file input we would need something like

FileInputStream inStream = new FileInputStream("input.data");
InputStreamReader reader = new InputStreamReader(inStream);
BufferedReader inFile    = new BufferedReader(reader);

or, more simply,

FileReader reader = new FileReader("input.data");
BufferedReader inFile = new BufferedReader(reader);

Similarly, for file output we would need something like

FileOutputStream outStream = new FileOutputStream("output.data");
OutputStreamWriter writer = new OutputStreamWriter(outStream);
PrintWriter outFile = new PrintWriter(writer);

or, more simply,

FileWriter writer = new FileWriter("output.data");
PrintWriter outFile = new PrintWriter(writer, true);

Once we have the inFile and outFile objects, we can use them as illustrated below.

// Copy lines from one file to another, adding line numbers
int lineCount = 0;
String inputLine = inFile.readLine();
while (inputLine != null)
{
    outFile.println("Line " + ++lineCount + ": " + inputLine);
    inputLine = inFile.readLine();
}
inFile.close();
outFile.close();

Note that it is good programming practice to close a stream once you are finished reading from it or writing to it.

Summary of Some Classes Used for File I/O

For Textfiles

Classes and Methods for Program Output to a Textfile

PrintWriter textOutFile = new PrintWriter("somefile.txt");
PrintWriter textOutFile = new PrintWriter(new FileOutputStream("somefile.txt"));
PrintWriter textOutFile = new PrintWriter(new FileOutputStream("somefile.txt", true));
textOutFile.print()
textOutFile.println()
textOutFile.printf()

textOutFile.close()

Classes and Methods for Program Input from a Textfile

Scanner textInFile = new Scanner(new File("somefile.txt"));
textInFile.nextInt()        textInFile.hasNextInt()
textInFile.nextDouble()     textInFile.hasNextDouble()
textInFile.next()           textInFile.hasNext()
textInFile.nextLine()       textInFile.hasNextLine()

textInFile.nextByte()       textInFile.hasNextByte()
textInFile.nextShort()      textInFile.hasNextShort()
textInFile.nextLong()       textInFile.hasNextLong()
textInFile.nextFloat()      textInFile.hasNextFloat()
textInFile.nextBoolean()    textInFile.hasNextBoolean()

textInFile.close()

For Binary Files

Classes and Methods for Program Output to a Binary File

ObjectOutputStream binaryOutFile = new ObjectOutputStream(new FileOutputStream("somefile.dat"));
ObjectOutputStream binaryOutFile = new ObjectOutputStream(new FileOutputStream(new File("somefile.dat")));
binaryOutFile.writeInt(someInt)
binaryOutFile.writeDouble(someDouble)
binaryOutFile.writeUTF(someString)
binaryOutFile.writeObject(someSerializableObject)

binaryOutFile.writeByte(someByte)
binaryOutFile.writeShort(someShort)
binaryOutFile.writeLong(someLong)
binaryOutFile.writeFloat(someFloat)
binaryOutFile.writeBoolean(someBoolean)

binaryOutFile.close()

Classes and Methods for Program Input from a Binary File

ObjectInputStream binaryInFile = new ObjectInputStream(new FileInputStream("somefile.dat"));
ObjectInputStream binaryInFile = new ObjectInputStream(new FileInputStream(new File("somefile.dat")));
someIntbinary = InFile.readInt()
someDouble = binaryInFile.readDouble()
someString = binaryInFile.readUTF()
someSerializableObject = (appropriate_cast)binaryInFile.readObject()

someByte = binaryInFile.readByte()
someShort = binaryInFile.readShort()
someLong = binaryInFile.raedLong()
someFloat = binaryInFile.readFloat()
someBoolean = binaryInFile.readBoolean()

binaryInFile.close()

A Class for Creating a File Object from Any File, and Some of Its Methods

The File Class

File f = new File("somefile.txt");

Some Methods of the File Class

Some Potential I/O-Related Exceptions

To be continued, with information on pipes and serialization ...