How to read file in Java – BufferedReader
Published: December 1, 2008 , Updated: February 3, 2012 , Author: mkyong
In Java, there are many ways to read a file, here we show you how to use the simplest and most common-used method – BufferedReader.
package com.mkyong.io; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class BufferedReaderExample { public static void main(String[] args) { BufferedReader br = null; try { String sCurrentLine; br = new BufferedReader(new FileReader("C:\\testing.txt")); while ((sCurrentLine = br.readLine()) != null) { System.out.println(sCurrentLine); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null)br.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }
See updated example in JDK 7, which use try-with-resources new feature to close file automatically.
package com.mkyong.io; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class BufferedReaderExample { public static void main(String[] args) { try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt"))) { String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { System.out.println(sCurrentLine); } } catch (IOException e) { e.printStackTrace(); } } }
Any Java questions or problems? please post at this JavaNullPointer.com forum, see you there ~
In your example, you should make sure to close the BufferedReader, otherwise the file may be lock not readable by some other process.
so
….
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
br.close();
…..
Example is updated, with new JDK7 example.
[...] visit How to read file from Java – BufferedReader Example 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 33 34 35 36 [...]