Home

Calendar

Staff

Help
Great Theoretical Ideas in Computer Science
BH 136A (the Adamson wing), TR 3:00-4:20P

Java: Reading from "Standard In"

Here is a bit of starter code, just as a quick aid to help java programmers that have never dealt with file input/output before. The code snippets that follow apply to reading from standard in, but can be applied to files as well. There are many ways to read in from standard in, but I feel that this is the easiest for this situation.

import java.io.*;

You always need to import java.io.*. As I hope you have seen, you write to System.out. As you might guess, you read from System.in. However, System.in provides little to make your life easy when it comes to reading in text. What we will do is wrap System.in as follows:

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

BufferedReader provides the function readLine(), which returns a line of text or null if the end of file has been reached. The end of file can be generated at the keyboard by pressing ctrl-D (in *nix) or ctrl-Z (in windows) for example. A complete program using a BufferedReader is:

import java.io.*;

public class Example {
	public static void main(String args[]) {
		BufferedReader reader = 
			new BufferedReader(new InputStreamReader(System.in));
		try {
			String temp;
			do {
				temp = reader.readLine();
				System.out.println(temp);
			} while (temp != null);
		} catch (IOException e) {
			System.out.println(e);
		}
	}
}

To use the program, I can run it with java Example, and it will expect input from the user, or I can run it and redirect a file to it like: java Example < Example.java. The latter is what the check script will do.



© 2006 Carnegie Mellon University, all rights reserved.