Use the right tool for the job. With Scanner
, it’s as simple as
List<String> list = new ArrayList<>();
try(Scanner s = new Scanner(Paths.get(path))) {
s.useDelimiter(Pattern.compile("^(?=REQ00)", Pattern.MULTILINE));
while(s.hasNext()) list.add(s.next());
} catch (IOException e) {
e.printStackTrace();
}
Now your code has the special requirements of creating StringBuilder
s and not retaining the line breaks. So the extended version is:
List<StringBuilder> list = new ArrayList<>();
try(Scanner s = new Scanner(Paths.get(path))) {
s.useDelimiter(Pattern.compile("^(?=REQ00)", Pattern.MULTILINE));
while(s.hasNext()) list.add(new StringBuilder(s.next().replaceAll("\\R", "")));
} catch (IOException e) {
e.printStackTrace();
}
A more efficient variant is
List<StringBuilder> list = new ArrayList<>();
try(Scanner s = new Scanner(Paths.get(path))) {
s.useDelimiter(Pattern.compile("^(?=REQ00)", Pattern.MULTILINE));
while(s.hasNext()) list.add(toStringBuilderWithoutLinebreaks(s.next()));
} catch (IOException e) {
e.printStackTrace();
}
…
static final Pattern LINE_BREAK = Pattern.compile("\\R");
static StringBuilder toStringBuilderWithoutLinebreaks(String s) {
Matcher m = LINE_BREAK.matcher(s);
if(!m.find()) return new StringBuilder(s);
StringBuilder sb = new StringBuilder(s.length());
int last = 0;
do { sb.append(s, last, m.start()); last = m.end(); } while(m.find());
return sb.append(s, last, s.length());
}
Starting with Java 9, you can also use a Stream
operation for it:
List<StringBuilder> list;
try(Scanner s = new Scanner(Paths.get(path))) {
list = s.useDelimiter(Pattern.compile("^(?=REQ00)", Pattern.MULTILINE))
.tokens()
.map(string -> toStringBuilderWithoutLinebreaks(string))
.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
list = List.of();
}