fileRead

fileRead - Reading/Writing Text Files Reading Text Files...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
Reading/Writing Text Files Reading Text Files: Instead of reading from the standard input, we can read from text files using the classes FileReader and 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 577 line = inFile.readLine(); while (line != null) { System.out.println(line); line = inFile.readLine(); } inFile.close(); } catch (FileNotFoundException exception) { System.out.println ("The file " + filename+ " was not found"); } catch (IOException exception) { System.out.println (exception); } } } The constructor of FileReader can throws FileNotFoundException if the file specified in the parameter is not located. reading it.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
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); } } } }
Background image of page 2
Writing Text Files:
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 7

fileRead - Reading/Writing Text Files Reading Text Files...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online