【问题标题】:How to read data in type 'integer' from file?如何从文件中读取“整数”类型的数据?
【发布时间】:2016-09-02 23:00:51
【问题描述】:

当我使用 Character.getNumericValue(c) 时,它可以理解 0-9 范围内的数字。但在文件中我有数字,例如:20、60、999 等 如何从文件中获取号码。

try (FileReader reader = new FileReader("D:\\input.txt")) {

        int c;
        while ((c = reader.read()) != -1) {

            int digit = Character.getNumericValue(c);

        }
    }

    catch (IOException ex) {

        System.out.println(ex.getMessage());
    }

【问题讨论】:

  • 您的文件是否只包含数字字符?
  • 是的,只有数字字符。

标签: java file input stream integer


【解决方案1】:
  1. 使用BufferedReader 包裹FileReader(装饰器模式)
  2. 使用bufferedReader.readLine() 读取行(在循环中)
  3. 使用String#split("\\s+") 根据空格拆分数据。
  4. 使用Integer.parseInt() 将每个拆分值(步骤3)解析为整数。

【讨论】:

    【解决方案2】:
    Scanner sc  = new Scanner(new File("D:\input.txt"));
    while(sc.hasNextInt()) {
      int n = sc.nextInt();
      System.out.println(n);
    }
    

    【讨论】:

    • ЮліяНечипорук 欢迎。如果解决了您的问题,请考虑接受答案。如果其他人遇到类似问题,我会帮助他们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多