Here, fileName specifies the name of the file that you want to open. When you create an
input stream, if the file does not exist, then FileNotFoundException is thrown. For output
streams, if the file cannot be created, then FileNotFoundException is thrown. When an
output file is opened, any preexisting file by the same name is destroyed.
When you are done with a file, you should close it by calling close( ). It is defined by
both FileInputStream and FileOutputStream, as shown here:
void close( ) throws IOException
To read from a file, you can use a version of read( ) that is defined within FileInputStream.
The one that we will use is shown here:
int read( ) throws IOException
Each time that it is called, it reads a single byte from the file and returns the byte as an integer
value. read( ) returns 1 when the end of the file is encountered. It can throw an IOException.
­
The following program uses read( ) to input and display the contents of a text file, the name
of which is specified as a command-line argument. Note the try/catch blocks that handle
two errors that might occur when this program is used--the specified file not being found
or the user forgetting to include the name of the file. You can use this same approach
whenever you use command-line arguments. Other I/O exceptions that might occur
are simply thrown out of main( ), which is acceptable for this simple example. However,
often you will want to handle all I/O exceptions yourself when working with files.
/* Display a text file.
To use this program, specify the name
of the file that you want to see.
For example, to see a file called TEST.TXT,
use the following command line.
java ShowFile TEST.TXT
*/
import java.io.*;
class ShowFile {
public static void main(String args[])
throws IOException
{
int i;
FileInputStream fin;
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println("File Not Found");
return;
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: ShowFile File");
return;
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home