【问题标题】:Read one number per line from file Java [closed]从文件 Java 中每行读取一个数字 [关闭]
【发布时间】:2020-07-30 18:10:10
【问题描述】:

所以我有一个文件,每行有两个数字代表坐标。如何每次都读取这两个数字并将它们放入 int 变量 x,y 中,忽略逐行的空格?

文件看起来像这样:(注意每一对都在不同的行)

8 23
130 28
23 108
50 99
108 107
52 54
115 107

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 我什么都没试过,因为这是我的问题。在 java 中有什么方法可以从文件中读取前两个整数并将它们放入 x 和 y 中,然后从下一行读取接下来的两个。
  • 你试过简单的分割吗?如String[] lines = text.split('\n'); 获取包含所有行的数组然后循环for(String line : lines) foreach 行。在循环内String[] coordinates = line.split(' ');。可能是这样的......
  • 那么您应该分小部分解决问题: 1. 了解如何从文件中读取文本。 2. 学习如何用空格分割字符串。 3. 最后学习如何将String 转换为int
  • 以文本为内容?文件的?另请注意(我没有提到它,我很抱歉)我不能(为了我的项目)使用 Files.readString(Paths.get(filename))。那么有没有其他的方式来获取文件内容呢?

标签: java file input stream


【解决方案1】:

下面是一个简单的例子,说明如何从名为input.txt 的文件中读取坐标并将它们解析为整数变量xy

    Stream<String> lines = Files.lines(Paths.get("input.txt"));
    lines.forEach(
            line -> {
                String[] split = line.split(" ");

                int x = Integer.parseInt(split[0]);
                int y = Integer.parseInt(split[1]);

                System.out.println("x = " + x);
                System.out.println("y = " + y);
            }
    );

或者不使用Files.lines():

    BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
    String line = reader.readLine();
    while (line != null) {

        String[] split = line.split(" ");

        int x = Integer.parseInt(split[0]);
        int y = Integer.parseInt(split[1]);

        System.out.println("x = " + x);
        System.out.println("y = " + y);

        // read next line
        line = reader.readLine();
    }
    reader.close();

【讨论】:

  • 这样可以完美运行,但不幸的是我不允许使用路径。
  • 你还有什么不能用的东西吗?
  • 没有。只是路径。这就是为什么我在阅读内容时遇到问题的原因。否则我会使用这个 Files.lines(Paths.get("input.txt"));
【解决方案2】:

你可以使用Scanner,但你需要双while循环

    FileReader fin = new FileReader("Test.txt");

    Scanner src = new Scanner(fin);
    while (src.hasNextLine()) {
        String line = src.nextLine();
        Scanner src2 = new Scanner(line);
        while(src2.hasNext()) {
            int n = src2.nextInt();
            System.out.print(n  + " ");
        }
        System.out.println();
    }

你也可以使用StreamTokenizer

【讨论】:

  • 非常感谢您的帮助,我会牢记这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多