Basics
- A File object has no methods to access file contents. The purpose of a File object is to provide Java access to the name of the file and its enclosing folders.
- Because a the construction of a new File may not work out -- the indicated name may be invalid, programs that use File objects must indicate as part of the method main() definition that it may throw IOExceptions
- public static void main( String[] args ) throws IOException
- public static void main( String[] args ) throws IOException
Important constructor for creating a File
- Suppose s is a String encoding the literal file name; e.g.,
- String s = "mydata.txt";
- String s = "mydata.txt";
- File f = new File( s );
- Makes f a variable giving a File view of the file name stored by s.
How to set up a Scanner to read from a File
- Suppose f iis a File.
- Scanner stream = new Scanner( f );
- Makes stream a variable giving a Scanner view of the file described by f.
- The statement
- int n = stream.nextInt();
- int n = stream.nextInt();
would read a number from file f.
- Makes stream a variable giving a Scanner view of the file described by f.