In this tutorial, we will learn to read a file or keyboard input in Java using BufferedReader
. You can use the given examples as a template and reuse/rewrite them the way you require.
1. BufferedReader class
The BufferedReader
reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines by minimizing the number of I/O operations.
1.1. Creating BufferedReder
To use a BufferedReader, we should wrap it around any Reader whose read() operations may be costly, such as FileReader and InputStreamReader.
BufferedReader in = new BufferedReader(new FileReader("foo.in"));
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Alternatively, we can directly get the BufferedReader reference using the NIO’s Files class.
BufferedReader reader =
Files.newBufferedReader(Paths.get("/path/file"))
1.2. Configuring Buffer Size
By default, BufferedReader uses a buffer of 8 KB. We can change the size of buffer while creating it, though the default size is good in most of the cases.
BufferedReader in = new BufferedReader(new FileReader("foo.in"), 65536); //64 KB buffer
2. Reading a File with BufferedReader
FileReader
class is used for reading streams of characters from a file. For reading streams of raw bytes, consider using a FileInputStream.
2.1. Reading a File Line by Line
try (BufferedReader bufferedReader
= new BufferedReader(new FileReader("/path/file"))) {
String currLine;
while ((currLine = bufferedReader.readLine()) != null) {
System.out.println(currLine);
System.out.println(System.lineSeparator());
}
}
catch (IOException e) {
e.printStackTrace();
}
2.2. Reading Console Input
InputStreamReader
class is used for reading the data from the underlying byte-input stream. Wrapping InputStreamReader
within a BufferedReader
provides the top efficiency.
try (BufferedReader reader
= new BufferedReader(new InputStreamReader(System.in)))
{
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
catch (IOException e) {
e.printStackTrace();
}
3. Conclusion
In this short Java tutorial, we learned to create and operate the BufferedReader instance in Java. We learned to configure the BufferedReader default buffer size. Also, we learned to read from file and system console.
Happy Learning !!
Comments