有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

字符串如何在java中从txt文件中读取冒号分隔的值

我试图从如下格式的文本文件中读取数据:

Operation: ADDITION Attempts: 3

我试图读入的数据是操作和每行的尝试次数,例如加法和数字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];
}

共 (3) 个答案

  1. # 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());
    
  2. # 2 楼答案

    最简单的选择是在空间上拆分:

    String[] parts = token.split(" ");
    String operation = parts[1];
    String attempts = parts[3];
    

    如果你想变得更时尚,可以使用正则表达式:

    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);
    }
    
  3. # 3 楼答案

    // 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"));
    }
    

    #1:使用Stream读取带有RegEx

    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());
    }
    

    #2:使用带有自定义分隔符的扫描仪读取对

    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;
        }
    }