有 Java 编程相关的问题?

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

java读取字母数字文本文件并尝试存储到列表或数组

我使用scanner.usedelimiter("[^0-9|,]")这个模式来避免文本文件中的字母。然后使用hasNext和next()方法存储到字符串,然后使用list,但list添加了额外的o和空格

我使用Scanner类读取一个文本文件,并从该文本文件中仅提取数字

Scanner sc = new Scanner("123.txt");
sc.useDelimiter("[^0-9|,|-]");
while (sc.hasNext()) {
    String s = null;
    s = sc.next();
    list.add(s.replaceAll("\\s+",""));
}

实际文件包含数据

Class   Student Details
1          total 25 students with 80% pass
2A - 3B          total 90 students with 70% pass
4A - 5B         total 69 students with 80% pass 10 distinction

预期产量

1 25 80
2 3 90 70
4 5  69 80 10

共 (3) 个答案

  1. # 1 楼答案

    另一种解决方案:不使用Scanner,您可以导入java.nio包,尤其是Files类:

    List<String> lines = Files.readAllLines(file.toPath()); 
    

    获得文件中所有行的列表后,可以对它们进行迭代,并用空格替换每个非数字:

    String s = line.replaceAll("[^0-9]+", " ");
    
  2. # 2 楼答案

    您可以将以下代码库与Java8特性结合使用

    public static void main(String[] args){
    
        String fileName = "D:\\data\\123.txt";
    
        try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
    
             stream.map(s -> s.replaceAll("[^0-9]+", " "))
                   .filter(s -> !s.trim().isEmpty())
                   .forEach(System.out::println);
    
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
  3. # 3 楼答案

    使用这样的123.txt文件:

    Class   Student Details
    1          total 25 students with 80% pass
    2A - 3B          total 90 students with 70% pass
    4A - 5B         total 69 students with 80% pass 10 distinction
    

    您可以使用正则表达式拆分每一行,只获取数字:

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Arrays;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.stream.Collectors;
    import java.util.Scanner;
    
    class Main {
        public static void main(String[] args) {
            List<List<Integer>> classDetails = new ArrayList<>();
            File file = new File("123.txt");
            try {
                Scanner scanner = new Scanner(file);
                scanner.nextLine(); // Skip header row
                while (scanner.hasNextLine()) {
                    String line = scanner.nextLine();
                    List<String> classNumbers = Arrays.asList(line.split("[^\\d]+"));
                    classDetails.add(classNumbers.stream()
                                                 .map(s -> Integer.parseInt(s))
                                                 .collect(Collectors.toList()));
                }
                scanner.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
    
            for (List<Integer> classNumbers : classDetails) {
                System.out.println(classNumbers);
            }
        }
    }
    

    输出:

    [1, 25, 80]
    [2, 3, 90, 70]
    [4, 5, 69, 80, 10]