go to previous page   go to home page   go to next page highlighting

Answer:

Yes. In fact, this is what is done with input redirection.


Input Stream from a File

scanner reading integers

With file input redirection, a disk file is connected to the standard input stream used by a Scanner object. You can construct a Scanner object that connects to a disk file:

// create a File object
File file = new File("myData.txt");

// connect a Scanner to the file
// (open the file for reading)
Scanner scan = new Scanner( file );      

These statements first create a File object. This is a software object that represents a file name. Creating a File object does not create a disk file. Next a Scanner object is constructed and connected to the actual file.

If the File object is constructed using just the file name (as here), then the disk file must be in the same disk directory as the running program.

Preparing a disk file for reading (which is what the above statements do) is called opening a file for reading. Creating a file and preparing it for writing is called opening a file for writing.

The same methods can be used with this Scanner object as with standard input. Characters than can be converted into an int can be scanned in using nextInt() as with the standard input stream.

Bug Alert! The following will not work:

Scanner scan = new Scanner( "myData.txt" );      

This creates a Scanner that scans through the String given as its argument.


QUESTION 3:

If a file can be opened, can a file also be closed?


go to previous page   go to home page   go to next page