假设我的输入文件包含:

3 4 5 6    7        8
9


10

我想运行while循环并读取整数,这样在循环的每次迭代后我将分别得到3,4,5,6,7,8和10。

在C / C ++中这很简单,但在Java中却没有...

我试过这段代码:

try {
            DataInputStream out2 = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));

            int i=out2.read();
            while(i!=-1){
                System.out.println(i);
                i=out2.readInt();
            }

    } catch (IOException ex) {

    }

我得到的是:

51
540287029
540418080
538982176
151599117
171511050
218762506
825232650

如何阅读 Java 文件的整数?

有帮助吗?

解决方案

可以使用 Scanner 类及其 nextInt 方法:

Scanner s = new Scanner("3  4        5   6");

while (s.hasNext()) {
  System.out.println(s.nextInt());
}

输出:

3
4
5
6

基本上默认情况下, Scanner 对象将忽略任何空格,并将获得下一个标记。

Scanner 类作为构造函数,它采用 InputStream 作为字符流的来源,因此可以使用 FileInputStream ,用于打开文本来源。

使用以下内容替换上例中的 Scanner 实例:

Scanner s = new Scanner(new FileInputStream(new File(filePath)));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top