BufferedReader
Read file with BufferedReader example
In this example we are going to see how to use use the BufferedReader
class in Java in order to read a simple text file. In Java, there is a number of ways that you can use to read a file, but the BufferedReader
class offers one the most efficient and easy to handle tools. Note that the BufferedReader
class can be used in order to read any kind of InputStream
.
Let’s see the code:
package com.javacodegeeks.java.core; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class BufferedReaderExample { private static String filepath = "C:\\Users\\nikos7\\Desktop\\words.txt"; public static void main(String[] args) { BufferedReader bufferedReader = null; try { String inputLine; bufferedReader = new BufferedReader(new FileReader(filepath)); while ((inputLine = bufferedReader.readLine()) != null) { System.out.println(inputLine); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (bufferedReader != null) { bufferedReader.close(); } } catch (IOException ex) { ex.printStackTrace(); } } } }
In JDK 1.7 you can also the try-with-resources
new super cool feature that automatically closes the stream:
package com.javacodegeeks.java.core; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class BufferedReaderExample { private static String filepath = "C:\\Users\\nikos7\\Desktop\\words.txt"; public static void main(String[] args) { try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filepath)) ){ String inputLine; while ((inputLine = bufferedReader.readLine()) != null) { System.out.println(inputLine); } } catch (IOException e) { e.printStackTrace(); } } }
So this will automatically execute the code in the finally
clause that we saw above.
The output of the above programs when we read a file with some words:
Output:
anatomy
animation
applet
application
argument
bolts
class
communicate
component
container
development
environment
exception
graphics
image
input
integrate
interface
Java
language
native
network
nuts
object
output
primer
program
security
stream
string
threads
tools
user
This was an example on how to use a BufferedReader to read from a File in Java.