17. FileReadWrite + Object Serialization(1) -...

This preview shows page 1 - 3 out of 7 pages.

Reading/Writing Text FilesReading Text Files:Instead of reading from the standard input, we can read from text files using the classes FileReaderand BufferedReader.import java.io.*;public class ReadingFromFile{public static void main (String[] args){String line, filename = “input.txt";try{FileReader fr = new FileReader (filename);BufferedReader inFile = new BufferedReader (fr);//Scanner inFile = new Scanner(fr); instead of the above// line = inFile.nextLine(); see page 577line = inFile.readLine();while (line != null){System.out.println(line);line = inFile.readLine();}inFile.close();}catch (FileNotFoundException exception){System.out.println ("The file " + filename+ " is not found");}catch (IOException exception){System.out.println (exception);}}}The parameter for the FileReader constructoris the name of a file to be read.The constructor of FileReader can throwsFileNotFoundException if the file specified inthe parameter is not located.It is a good practice to close the file after finishingreading it.1
Note that the previous code can be done a little more formally as follows.All other examples are rather simplified in this notes, but it can be expanded to be more robust.import java.io.*;public class ReadingFromFile{public static void main (String[] args){String line, filename = "input.txt";FileReader fr = null;BufferedReader inFile = null;try{fr = new FileReader (filename);inFile = new BufferedReader (fr);line = inFile.readLine();while (line != null){System.out.println(line);line = inFile.readLine();}}catch (FileNotFoundException exception){System.out.println ("The file " + filename + " was not found");}catch (IOException exception){System.out.println (exception);}finally{try{if (inFile != null)inFile.close();}catch (IOException ex){System.out.println(ex);}}}}2

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture