Pages

Monday, June 18, 2012

Buffered reader

In many times you will read data from some device or file, like a keyboard, a serial port or a txt file. For all those devices, you will need a BufferedReader object. This object allows you to put in all the information you want to read, and then get it by characters or lines. Whatever you need to read, you can pass it to the BufferedReader when you instancied it, and then you can read its data when you need. Here is an example:
System.out.println("Write something you want to read., and press Enter.");
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
String data = keyboard.readLine();
In the previous code I use the InputStreamReader to get access to the keyboard (System.in). I will explain it more deeply in another article. When the "readLine()" method is call, the execution of the code will stop there until the user enter some data in the console and press Enter. The user must press Enter to finish the line, because the ejecution will not continue until there is a complete line in the BufferedReader. All the data written in the console from the keyboard will be stored in the variable "data" as a string.

Lets examine the different method of the BufferedReader. The BufferedReader can read its content line by line, as it was shown before, but it can read it char by char or a specified number of characters. Another way is specifiyng a token or mark. When you read char by char, the mark will move ahead. Then you can skip some characters you don't want to read, or you can reset this mark to the beginning of the buffer. Here are some examples:

File.txt:
Hello, this is a file.
There are many lines in this file.
But this is the last one.

Code:
String a; char[] b = new char[10]; int c;
BufferedReader file = new BufferedReader(new FileReader("File.txt"));
a = file.readLine();
System.out.println("First read: " + a);
c = file.read(b, 0, 10);
System.out.println("Second read, " + c + " characters read: " + new String(b));
file.reset();
file.skip(7);
a = file.readLine();
System.out.println("Last read: " + a);

Output:
First read: Hello, this is a file.
Second read, 10 characters read: There are
Last read: this is a file.
Reading something with a BufferedReader can throw some exception, so every time the read methods must be inside a try/catch clause.

1 comment: