Read from a file using a BufferedReader
For reading text from a file it's better to use a Reader class instead of a InputStream class since Reader classes have the purpose of reading textual input. In this example we use the BufferedReader class to read text from a file line by line using it's readLine method. It is possible to read the data the same way as with the BufferedInputStream using either a byte array or read one byte at a time, but if you're going to read plain text this is easier and produce more readable code. In the example we simply create a BufferedReader object and start reading from the file line by line until the readLine method returns null, which indicates the end of the file. |
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /** * * @author javadb.com */ public class Main { /** * Reads text from a file line by line */ public void readFromFile(String filename) { BufferedReader bufferedReader = null; try { //Construct the BufferedReader object bufferedReader = new BufferedReader(new FileReader(filename)); String line = null; while ((line = bufferedReader.readLine()) != null) { //Process the data, here we just print it out System.out.println(line); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { //Close the BufferedReader try { if (bufferedReader != null) bufferedReader.close(); } catch (IOException ex) { ex.printStackTrace(); } } } /** * @param args the command line arguments */ public static void main(String[] args) { new Main().readFromFile("myFile.txt"); } } |
See this example if you want to compare with reading from a BufferedInputStream: |
| Read from file with BufferedInputStream |
| Do you know your Java? | |
| Take a Ten-Question-Java-Quiz! | |
Bookmark:
Search for code examples on this site
