I need to read a text file line by line using Java. I use available()
method of FileInputStream
to check and loop over the file. But while reading, the loop terminates after the line before the last one. i.e., if the file has 10 lines, the loop reads only the first 9 lines.
Snippet used :
while(fis.available() > 0)
{
char c = (char)fis.read();
.....
.....
}
If you want to read line-by-line, use a
BufferedReader
. It has areadLine()
method which returns the line as a String, or null if the end of the file has been reached. So you can do something like:(Note that this code doesn't handle exceptions or close the stream, etc)
You can try FileUtils from org.apache.commons.io.FileUtils, try downloading jar from here
and you can use the following method: FileUtils.readFileToString("yourFileName");
Hope it helps you..
user scanner it should work
You should not use
available()
. It gives no guarantees what so ever. From the API docs ofavailable()
:You would probably want to use something like
(taken from http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html)