Back to ICS211

Mobius strip

Java I/O

Java input and output is accomplished using the classes in the java.io package. You can learn more about them in the Java API.

The four most common I/O problems you will face are writing to the screen, reading from the keyboard, and reading and writing to a file.

Writing to the Screen

You already know how to do this--just write to System.out:

System.out.print("Text to the screen.");
System.out.println("Text to the screen with a newline after it.");

Reading User Input from the Keyboard

BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String userInput = stdin.readLine();

Reading from a file

BufferedReader filein = new BufferedReader(new FileReader("samplefile.txt"));
String nextLine = filein.readLine();
filein.close();

Writing to a file

PrintWriter fileout = new PrintWriter(new FileWriter("samplefile.txt"));
fileout.write("Some text I want in the file.\n");
fileout.close();


When performing the last three operations--keyboard input, file input, and file output--you will need to catch IOExceptions.

You can use different variable names for your BufferedReaders and PrintWriters than I have here. Also, you may have code between opening a stream, writing or reading to the stream, and closing the stream. Remember to close any file streams you open. This is especially important when writing to a file, since all your output may not be stored in the file if you forget to flush() or close() the stream.

It is also possible to use Java streams to read or write to other devices besides the hard disk, or to access resources across a network. We won't be covering such details in this course, but you can learn more from the Java API, the Java Tutorial, or a good book on Java programming.

Example Code

FileViewer.java
This program reads from a file and displays text to the screen.
FileAppender.java
This program gets user input from the keyboard and writes text to a file. It uses a different constructor than the example above because it appends to the file, rather than overwriting it.

Both of these example programs also show how to process command line arguments.



~ztomasze Index : TA Details: ICS211: Java I/O
http://www2.hawaii.edu/~ztomasze
Last Edited: 29 Sept 2004
©2002 by Z. Tomaszewski.