从 Java 中的 txt 文件获取整数数据

Getting integer data from txt file in Java

我想读取一个文本文件,其中包含字符串和一些与该字符串相关的整数。

这是我必须在其中编写程序的 class:

public List<Integer> Data(String name) throws IOException {
    return null;
}

我必须阅读 .txt 文件并在该文件中找到名称及其数据。并将其保存在 ArrayList 中。

我的问题是当我在 List 中有 String 时如何将它保存在 ArrayList<Integer> 中。
这就是我想我会做的:

Scanner s = new Scanner(new File(filename));
ArrayList<Integer> data = new ArrayList<Integer>();

while (s.hasNextLine()) {
    data.add(s.nextInt());
}
s.close();

我会将文件定义为一个字段(除了 filename,我建议从用户的主文件夹中读取它)file

private File file = new File(System.getProperty("user.home"), filename);

然后您可以在定义 List 时使用菱形运算符 <>。您可以使用 try-with-resourcesclose 您的 Scanner。你想按行阅读。你可以 split 你的 line。然后测试第一列是否与名称匹配。如果是,则迭代其他列并将它们解析为 int。像

public List<Integer> loadDataFor(String name) throws IOException {
    List<Integer> data = new ArrayList<>();
    try (Scanner s = new Scanner(file)) {
        while (s.hasNextLine()) {
            String[] row = s.nextLine().split("\s+");
            if (row[0].equalsIgnoreCase(name)) {
                for (int i = 1; i < row.length; i++) {
                    data.add(Integer.parseInt(row[i]));
                }
            }
        }
    }
    return data;
}

扫描文件一次并将名称和字段存储为 Map<String, List<Integer>> 类似

的效率可能会显着提高
public static Map<String, List<Integer>> readFile(String filename) {
    Map<String, List<Integer>> map = new HashMap<>();
    File file = new File(System.getProperty("user.home"), filename);
    try (Scanner s = new Scanner(file)) {
        while (s.hasNextLine()) {
            String[] row = s.nextLine().split("\s+");
            List<Integer> al = new ArrayList<>();
            for (int i = 1; i < row.length; i++) {
                al.add(Integer.parseInt(row[i]));
            }
            map.put(row[0], al);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return map;
}

然后像

一样将其存储为fileContents
private Map<String, List<Integer>> fileContents = readFile(filename);

然后用 fileContents 实现你的 loadDataFor(String) 方法,比如

public List<Integer> loadDataFor(String name) throws IOException {
    return fileContents.get(name);
}

如果您的使用模式读取多个名称的 File,那么第二个可能会快得多。

如果你想使用 java8 你可以使用这样的东西。

Input.txt(必须在类路径中):

text1;4711;4712
text2;42;43

代码:

public class Main {

    public static void main(String[] args) throws IOException, URISyntaxException {

        // find file in classpath
        Path path = Paths.get(ClassLoader.getSystemResource("input.txt").toURI());

        // find the matching line
        findLineData(path, "text2")

                // print each value as line to the console output
                .forEach(System.out::println);
    }

    /** searches for a line in a textfile and returns the line's data */
    private static IntStream findLineData(Path path, String searchText) throws IOException {

        // securely open the file in a "try" block and read all lines as stream
        try (Stream<String> lines = Files.lines(path)) {
            return lines

                    // split each line by a separator pattern (semicolon in this example)
                    .map(line -> line.split(";"))

                    // find the line, whiches first element matches the search criteria
                    .filter(data -> searchText.equals(data[0]))

                    // foreach match make a stream of all of the items
                    .map(data -> Arrays.stream(data)

                            // skip the first one (the string name)
                            .skip(1)

                            // parse all values from String to int
                            .mapToInt(Integer::parseInt))

                    // return one match
                    .findAny().get();
        }
    }
}

输出:

42
43