Your code has multiple issues like @Henry said that your string contains only the last line of the file and also you misunderstood the split()
because it takes a RegularExpression as a parameter.
I would recommend you to use the following example because it works and is a lot faster than your approach.
Kick-Off example:
// create a buffered reader that reads from the file
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt")));
// create a new array to save the lists
ArrayList<String> lists = new ArrayList<>();
String list = ""; // initialize new empty list
String line; // initialize line variable
// read all lines until one becomes null (the end of the file)
while ((line = reader.readLine()) != null) {
// checks if the line only contains one *
if (line.matches("\\s*\\*\\s*")) {
// add the list to the array of lists
lists.add(list);
} else {
// add the current line to the list
list += line + "\r\n"; // add the line to the list plus a new line
}
}
Explanation
I'm going to explain special lines that are hard to understand again.
Looking at the first line:
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt")));
This line creates a BufferedReader
that is nearly the same like a Scanner
but it's a lot faster and hasn't as much methods as a Scanner
. For this usage the BufferedReader
is more than enough.
Then it takes an InputStreamReader
as a parameter in the constructor. This is only to convert the following FileInputStream
to a Reader
.
Why should one do that? That's because an InputStream
≠ Reader
. An InputStream
returns the raw values and a Reader
converts it to human readable characters. See the difference between InputStream
and Reader
.
Looking at the next line:
ArrayList<String> lists = new ArrayList<>();
Creates a variable array that has methods like add()
and get(index)
. See the difference of arrays and lists.
And the last one:
list += line + "\r\n";
This line adds the line
to the current list and adds a new line to it.
"\r\n"
Are special characters. \r
ends the current line and \n
creates a new line.
You could also only use \n
but adding \r
in front of it is better because this supports more Os's like Linux can have problems with it when \r
misses.
Related
Using BufferedReader to read Text File