File IO CSCI 392 Adapted from Dannelly Code

  • Slides: 5
Download presentation
File I/O CSCI 392 Adapted from Dannelly

File I/O CSCI 392 Adapted from Dannelly

Code Samples Reading Text – n The first example opens a file named "input.

Code Samples Reading Text – n The first example opens a file named "input. Day 4. txt", reads one line of text into a sting, and prints the string to the screen. n 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. n Also note that throws IOException was added to main's declaration. These opening and reading functions can create an exception. Since an exception can not be ignored, we must indicate how the exception will be dealt with. In this example the exception is passed up to who ever called main - ie. I pass the buck.

Writing Text n The second example opens the file "ouput. txt", writes one line

Writing Text n The second example opens the file "ouput. txt", writes one line of text, then closes the file. n 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. n The second version, commented out, will keep the existing contents and add to the end of the file. n

Reading Text from keyboard and Numbers from a file n The third example opens

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

Catching an Exception The fourth example catches the IOException that might come from the

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.