一个更好的解决方案(第三次尝试),它(希望)能更好地处理大文件,因为它避免了将整个文件读入缓冲区:
public static void main(String[] args) throws IOException {
String input = "[04/06/2021] Some text\n" +
"some more text\n" +
"even more text\n" +
"[01/01/2020] Some text \n" +
"[31/12/2020] More text\n" +
"Final text block";
List<String> testList = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new StringReader(input))) {
br.lines().forEach(
line -> {
if (testList.isEmpty() || line.startsWith("[")) {
testList.add(line + " ");
} else {
testList.set(
testList.size() - 1,
testList.get(testList.size() - 1) + line + " ");
}
}
);
}
testList.forEach(System.out::println);
}
我想出了这个乏味的方法:
public static void main(String[] args) throws IOException {
String input = "[04/06/2021] Some text\n" +
"some more text\n" +
"even more text\n" +
"[01/01/2020] Some text \n" +
"[31/12/2020] More text\n" +
"Final text block";
List<String> testList = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new StringReader(input))) {
String nextLine = br.readLine();
StringBuilder currentLine = new StringBuilder(nextLine + " ");
while (nextLine != null) {
nextLine = br.readLine();
if (nextLine != null) {
if (nextLine.startsWith("[")) {
testList.add(currentLine.toString());
currentLine = new StringBuilder();
}
currentLine.append(nextLine).append(" ");
}
}
if (currentLine.length() > 0) {
testList.add(currentLine.toString());
}
}
testList.forEach(System.out::println);
}
如果您可以摆脱循环,则更好/更简单的方法是:
public static void main(String[] args) throws IOException {
String input = "[04/06/2021] Some text\n" +
"some more text\n" +
"even more text\n" +
"[01/01/2020] Some text \n" +
"[31/12/2020] More text\n" +
"Final text block";
List<String> testList = new ArrayList<>();
String[] inputs = input.split("\\n");
StringBuilder currentLine = new StringBuilder(inputs[0] + " ");
for (int i = 1; i < inputs.length; i++) {
if (inputs[i].startsWith("[")) {
testList.add(currentLine.toString());
currentLine = new StringBuilder();
}
currentLine.append(inputs[i]).append(" ");
}
testList.add(currentLine.toString());
testList.forEach(System.out::println);
}
输出:
[04/06/2021] Some text some more text even more text
[01/01/2020] Some text
[31/12/2020] More text Final text block