Tag Archives: file i/o

Reading From a File in Java

Simple Example :

  1:import java.io.*;
   2:
   3:public class ReadFile{
   4:    public static void main(String[] args){
   5:        try {
   6:            
   7:            /*  Sets up a file reader to read the file passed on the command
   8:                line one character at a time */
   9:            FileReader input = new FileReader(args[0]);
  10:            
  11:            /* Filter FileReader through a Buffered read to read a line at a
  12:               time */
  13:            BufferedReader bufRead = new BufferedReader(input);
  14:            
  15:            String line;    // String that holds current file line
  16:            int count = 0;  // Line number of count 
  17:            
  18:            // Read first line
  19:            line = bufRead.readLine();
  20:            count++;
  21:            
  22:            // Read through file one line at time. Print line # and line
  23:            while (line != null){
  24:                System.out.println(count+": "+line);
  25:                line = bufRead.readLine();
  26:                count++;
  27:            }
  28:            
  29:            bufRead.close();
  30:            
  31:        }catch (ArrayIndexOutOfBoundsException e){
  32:            /* If no file was passed on the command line, this expception is
  33:            generated. A message indicating how to the class should be
  34:            called is displayed */
  35:            System.out.println("Usage: java ReadFile filename\n");          
  36:
  37:        }catch (IOException e){
  38:            // If another exception is generated, print a stack trace
  39:            e.printStackTrace();
  40:        }
  41:        
  42:    }// end main
  43:}

referenced from Abbey Workshop
Advertisements

Leave a comment

Filed under Java