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

6

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

这是我需要编写程序的类:

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

2
你想把字符串转换为整数吗? - Alexander
2个回答

3

我认为文件应该被定义为一个字段(除了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,那么第二个选项可能会更快。

0
如果您想使用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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接