1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | package ebhor.io; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class FileReading { public static void main(String[] args) { String line; BufferedReader br=null; try { FileReader fr = new FileReader("D:\\first.txt"); br = new BufferedReader(fr); while ((line = br.readLine()) != null) { System.out.println(line); } } catch (FileNotFoundException e) { System.out.println("File not found " + e); } catch (IOException e) { System.out.println("IO Error " + e); } finally { if (br != null) { try { br.close(); } catch (IOException ex) { System.out.println("File not closed " + ex); } } } } |
For reading a file we have to create a FileReader object.
Then we create BufferedReader object of FileReader.
If file not found FileReader constructor throws FileNotFoundException.
If br.readLine() is not able to read source file it throws IOException.