Files and I/O (Cont.)


Reading a File
In the following example, we use the Scanner class to read the contents of the text file we created in the previous example:

ReadFile.java (reading a file)

 import java.io.File;
 import java.io.FileNotFoundException;
 import java.util.Scanner;

 public class ReadFile {
   public static void main( String[ ] args ) {
     try {
       File myObj = new File( args[0] );
       Scanner myReader = new Scanner( myObj );
       while ( myReader.( ) ) {
         String data = myReader.( );
         System.out.println( data );
       }
       myReader.close( );
     }
     catch ( FileNotFoundException e ) {
       System.out.println( "An error occurred." );
       e.printStackTrace( );
     }
   }
 }
shell> java ReadFile            

Some of the file classes are given next (cont.):