Example - Read a Text File
import java.io.BufferedReader; import java.io.IOException; import java.io.FileNotFoundException; import java.io.FileReader; public class FileRead { public static void main(String[] args) { String instr; try { // use 1st command line argument as file name FileReader fin = new FileReader(args[0]); BufferedReader filein = new BufferedReader(fin); // read each line of file into a String and print the string // readLine returns null at end of file instr = filein.readLine(); while (instr != null) { System.out.println(instr); instr = filein.readLine(); } filein.close(); } catch(FileNotFoundException e) { System.out.println("Error: file " + args[0] + " not found"); } catch(IOException e) {} } }Input File:
C:\cafe1.8\Mine>type fileread.in first line of file here is the second line next are some numbers 33 44 55 66 last lineOutput:
C:\cafe1.8\Mine>java FileRead fileread.in first line of file here is the second line next are some numbers 33 44 55 66 last line C:\cafe1.8\Mine>java FileRead another Error: file another not found
Email Me | Office Hours | My Home Page | Department Home | MCC Home Page