Problem description: For example we have a text file file.txt with following content:
Hello(LS)
what(LS)
are(LS)
<empty_line>(LS)
you(LS)
doing(LS)
<empty_line>(LS)
<empty_line>(LS)
now(LS)
<empty_line>(LS)
<empty_line>(LS)
<empty_line>(EOF)
(LS - line separator, EOF - end of file)
If I understood the idea of text file, the file is looking something like that. Now, I want to fill up for example TextArea (from JavaFX) with this text. I can use the following code surrounded with try-catch (close() method would be in finnaly block):
TextArea textArea = new TextArea();
BufferedReader br = new BufferedReader(new FileReader(new File("file.txt")));
String line;
while ((line = br.readLine()) != null) {
textArea.appendText(line);
textArea.appendText("\n");
}
That code has one big problem - everytime there is one more line in the targeted TextArea when text file does't ending with empty_line. When file that empty_line contains before EOF, so loading into TextArea is working right. I tried a lot of way how to do it, but everytime there was some problems.
Why I chose BufferedReader? I chose BufferedReader because I just want some reader that can reads source text file line by line. I want that reader, because of file separator and OS independence.
What I expect from it?
I am awaiting that I read file line by line and when I am reading I set up custom separators (independently for source file line separators) - for example LF ("\n"). And I am awaiting exactly the same content with possible different line separators! When I am writing to some file (where I am using BufferedReader
too (for intern reading text from TextArea and set up line separators depended on user OS (System.getProperty("line.separator")
)) there is a similar behavioral.
What I tried? I tried a lot of ways how to do it. I also tried use method read() in class BufferedReader and compare it's return value with -1, which is means EOF. BUT, there is one problem, I want to use custom file separators and I don't have all time to write some parsers.
My question: How can I write to TextArea (or any String) the file content with customed line separators without any extra or less line?
*As you can see, my english isn't very good, so I hope you understand me, thanks.
As it turned out in the discussion, the problem is that with
readLine()
the following files will behave the same way:Solution: use other methods to read the characters, two of them explained here:
One character at a time:
Buffered: