Read lines of text from a file with the BufferedReader class
This example shows how to read the contents of a file line by line. By using the BufferedReader class we can read line-by-line without having to worry about linebreaks. We just call it's readLine() method. |
package je_test; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class FileUtil { public void readLinesFromFile(String filename) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(filename)); String line = null; while ((line = br.readLine()) != null) { //Process the line just read. //Here we just echo it to standard output. System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } finally { //Close the BufferedReader if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static void main(String[] args) { FileUtil util = new FileUtil(); util.readLinesFromFile("myfile.txt"); } } |
| Do you know your Java? | |
| Take a Ten-Question-Java-Quiz! | |
Bookmark:
Search for code examples on this site
