如何在Java中读取格式化输入?

假设我的输入文件包含:

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