How to open a txt file and read numbers in Java

后端 未结 6 1048
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 18:17

How can I open a .txt file and read numbers separated by enters or spaces into an array list?

6条回答
  •  借酒劲吻你
    2020-11-27 18:47

    A much shorter alternative is below:

    Path filePath = Paths.get("file.txt");
    Scanner scanner = new Scanner(filePath);
    List integers = new ArrayList<>();
    while (scanner.hasNext()) {
        if (scanner.hasNextInt()) {
            integers.add(scanner.nextInt());
        } else {
            scanner.next();
        }
    }
    

    A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. Although default delimiter is whitespace, it successfully found all integers separated by new line character.

提交回复
热议问题