Monday, February 2, 2009

Java readLine Problem

A problem with using the readLine method to read the contents of the file is that you never know whether the last line in the file has a line break at the end. The readLine method can return either due to a line break or due to the end of the file so when you don't know which, you can either add a line break in which case you could be adding an extra character to the file, or you can assume that there was no line break in which case you may be removing a character from the end of the file.

If you're building a text editor (such as nText, an open-source project hosted on SourceForge... I committed a fix to the project already), checksum utility, or anything along those lines that are sensitive to the EOF/EOL issue, you really ought to stop using readLine and use a regular read with a character array instead.

This could've been solved by including a readToEnd method that developers are more likely to want to use than the readLine method.

2 comments:

vivekcis said...

Nice post. I also faced the same issue. Actually i have created a notepad application and i want to open an already created file so it doesn't show the line break and show the contents of file without any paragraphs. These kind of issues known by only those individuals who really worked. So these kind of questions should be asked in interviews if you want to hire php programmer, java programmers or any other programmer.

Richard Byrdk said...
This comment has been removed by the author.