The java.io Package
Package
java.io includes a number of uniform input and output (I/O) operations that allow you to send and receive data. The source or destination of this data can be virtually anything—input from the keyboard, output to the monitor, files, even server-client architectures. The magic behind Java I/O is achieved through what are called streams. A stream is simply a sequence of characters or bytes that is either read from a source or written to a destination.
Java I/O starts with two abstract classes called
java.io.Reader and
java.io.Writer. All further I/O operations are implemented in subclasses that extend their functionality. Rather than going into the nitty-gritty on how these classes work, consider an example of how you can use them.
One way you can input information from the user is by using the
BufferedReader class. Buffering input saves Java from converting each character as it is read, therefore increasing throughput. You can use the
BufferedReader class, for example, to read information from the monitor or from a file. The following program demonstrates how you can use the
BufferedReader class to input an integer from the user:
// create a new BufferedReader that takes input from standard input
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
boolean validInput = false; // flags "good" input
// prompt the user to enter an integer
System.out.print("Enter an integer value: ");
// loop until the user enters valid input
while(!validInput)
{
// assume input will be valid until we prove otherwise
validInput = true;
try
{
String input = reader.readLine();
Try
{
// if parseInt cannot properly parse the String, a
// NumberFormatException is thrown
int i = Integer.parseInt(input);
System.out.println("You typed the number: " + i);
}
catch(NumberFormatException e)
{
// set our valid flag to false and prompt for input
validInput = false;
System.out.print("Invalid, redo: ");
}
}
catch(IOException e)
{
// if reading from standard should fail, print an error message and
// terminate the program
System.out.println("IOException caught- Program terminating");
System.exit(-1);
}
}
The above program prompts the user to input an integer until he or she enters valid data. The following may be sample run of this program:
Enter an integer value: integer
Invalid, redo: value
Invalid, redo: huh?
Invalid, redo: 873!!!!
Invalid, redo: -2
You typed the number: -2
As you can see, the above code includes lots of exception handling. That is why it is always a good idea to methodize such utilities. It will save you lots of coding in the future.