File IO

Here are four short code examples that use files.

Reading Text - The first example simply opens a file named "input.txt", reads one line of text into a sting, and prints the string to the screen. Note that file input works just like input from the keyboard: you read strings. So, if you want to read a number, you must convert the string into a number.

Also note that throws IOException was added to main's declaration. These opening and reading functions can create an execption. Since an exception can not be ignored, we must indicate how the exception will be dealt with. In this example I chose to pass the exception up to who ever called main - ie. I pass the buck.

Writing Text - The second example opens the file "ouput.txt", writes one line of text, then closes the file. There are two versions of the command that connects to the file. The first version will cause any older version of the file to be erased before writing begins. The second version, commented out, will keep the existing constents and just add to the end of the file.

Reading Text from keyboard and Numbers from a file - The third example prompts the user for a file name, reads that file name from the keyboard, opens that file, then reads an unknown number of integers from that file, and finally outputs thier sum. The best way to read until end-of-file, is to call readLine until it returns null (no more strings can be read).

Catching an Exception - The fourth example catches the IOException that might come from the connecting function. If the file does not exist, the program prints an error and stops. Note that main still throws an exception.