[英]Read lines from file between delimiters
For example, if I have a file like this: 例如,如果我有一个像这样的文件:
SECTION 1
Some text
SECTION 2
Some more text
Aother line of text
SECTION 1
Some text
Another line
SECTION 2
Another line here
How can I read the lines between each section (where each section can have up to dozens of lines each)? 如何阅读每个部分之间的行(每个部分最多可以包含数十行)? Here's what I currently have:
这是我目前拥有的:
public static void main(String[] args) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("section_text.txt"));
String line;
while (br.readLine() != null) {
line = br.readLine().trim();
}
br.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
while (line = br.readLine() != null) {
if(line.contains("SECTION")){
// do something with those "SECTION" lines ...
} else {
// do something with other non-SECTION lines ...
}
}
Assuming you want to process the lines for each section as a block, try this (empty sections are ignored): 假设您希望将每个部分的行作为一个块进行处理,请尝试以下操作(空部分将被忽略):
public static void main(String[] args) throws Exception {
try (BufferedReader br = new BufferedReader(new FileReader("section_text.txt"))) {
String line, section = null;
List<String> lines = new ArrayList<>();
while ((line = br.readLine()) != null) {
if (line.startsWith("SECTION ")) {
if (! lines.isEmpty())
processSection(section, lines);
section = line.substring(8).trim();
lines = new ArrayList<>();
} else {
lines.add(line.trim());
}
}
if (! lines.isEmpty())
processSection(section, lines);
}
}
private static void processSection(String section, List<String> lines) {
// code here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.