Java IO: LineNumberReader
Jakob Jenkov |
The Java LineNumberReader
class (java.io.LineNumberReader
is a
BufferedReader
that keeps track of line numbers of the read characters. Line numbering begins at 0.
Whenever the LineNumberReader
encounters a line terminator in the characters returned by the wrapped
Reader
, the line number is incremented.
You can get the current line number from the LineNumberReader
by calling the getLineNumber()
method. You can also set the current line number, should you need to, by calling the setLineNumber()
method.
LineNumberReader Example
Here is a simple Java LineNumberReader
example:
LineNumberReader lineNumberReader = new LineNumberReader(new FileReader("c:\\data\\input.txt")); int data = lineNumberReader.read(); while(data != -1){ char dataChar = (char) data; data = lineNumberReader.read(); int lineNumber = lineNumberReader.getLineNumber(); } lineNumberReader.close();
This example first creates a LineNumberReader
, and then shows how to read all the characters from it,
and also shows how to get the line number (for each character read, in fact, which may be a bit more than you need).
Line Numbers in Parsing
Line number can be handy if you are parsing a text file that can contain errors. When reporting the error to the user, it is easier to correct the error if your error message includes the line number where the error was encountered.
Closing a LineNumberReader
When you are finished reading characters from the LineNumberReader
you should remember to close it.
Closing a LineNumberReader
will also close the Reader
instance from which the
LineNumberReader
is reading.
Closing a LineNumberReader
is done by calling its close()
method. Here is how
closing a LineNumberReader
looks:
lineNumberReader.close();
You can also use the try-with-resources construct
introduced in Java 7. Here is how to use and close a LineNumberReader
looks with the try-with-resources
construct:
Reader reader = new FileReader("data/text.txt"); try(LineNumberReader lineNumberReader = new LineNumberReader(reader)){ String line = lineNumberReader.readLine(); while(line != null) { //do something with line line = lineNumberReader.readLine(); } }
Notice how there is no longer any explicit close()
method call. The try-with-resources construct
takes care of that.
Notice also that the first FileReader
instance is not created inside
the try-with-resources block. That means that the try-with-resources block will not automatically close this
FileReader
instance. However, when the LineNumberReader
is closed
it will also close the Reader
instance it reads from, so the FileReader
instance will get closed when the LineNumberReader
is closed.
Tweet | |
Jakob Jenkov |