我正在尝试从格式如下的文本文件中读取数据:
Operation: ADDITION Attempts: 3
我要读取的数据是操作和每行的尝试次数,例如ADDITION和数字3
就我所能达到的程度,我仍然不确定。
File inputFile = new File("mathFile.txt");
Scanner input = new Scanner(inputFile);
while(input.hasNext())
{
String token = input.nextLine();
String[] details = token.split("Operation:");
String operation = details[0];
}
答案 0 :(得分:0)
// Model: line representation
public final class MathFileLine {
private final String operation;
private final int attempts;
public MathFileLine(String operation, int attempts) {
this.operation = operation;
this.attempts = attempts;
}
}
// client code
public static void main(String... args) throws IOException {
List<MathFileLine> lines = readMathFile(Paths.get("mathFile.txt"));
}
public static List<MathFileLine> readMathFile(Path path) throws IOException {
final Pattern pattern = Pattern.compile("^Operation:\\s+(?<operation>\\w+)\\s+Attempts:\\s+(?<attempts>\\d+)$");
return Files.lines(path)
.map(pattern::matcher)
.filter(Matcher::matches)
.map(matcher -> new MathFileLine(matcher.group("operation"), Integer.parseInt(matcher.group("attempts"))))
.collect(Collectors.toList());
}
public static List<MathFileLine> readMathFile(Path path) throws IOException {
try (Scanner scan = new Scanner(path.toFile())) {
scan.useDelimiter("\\s*(?:Operation:|Attempts:)?\\s+");
List<MathFileLine> lines = new LinkedList<>();
while (scan.hasNext()) {
lines.add(new MathFileLine(scan.next(), scan.nextInt()));
}
return lines;
}
}
答案 1 :(得分:0)
最简单的选择是分割空格:
String[] parts = token.split(" ");
String operation = parts[1];
String attempts = parts[3];
如果想发烧友,可以使用Regex:
String token = "Operation: ADDITION Attempts: 3";
Matcher matcher = Pattern.compile("^Operation: (\\w+) Attempts: (\\d+)$").matcher(token);
if (matcher.find()) {
String operation = matcher.group(1);
String attempts = matcher.group(2);
}
答案 2 :(得分:-1)
您可以通过多种方式读取文本文件并根据一些定界符来分割行。除了这里的所有其他答案外,以下是另一个简洁明了的答案。
(1)读取文件的行
List<String> lines = Files.lines(Paths.get("mathFile.txt")).collect(Collectors.toList());
(2)从每一行中解析您想要的内容
List<String> operations = lines.stream().map(line -> line.split("Operation:")[0]).collect(Collectors.toList());