简体   繁体   English

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

[英]How do I read formatted input in Java?

Suppose my input file contains: 假设我的输入文件包含:

3 4 5 6    7        8
9


10

I want to run a while loop and read integers, so that I will get 3,4,5,6,7,8 and 10 respectively after each iteration of the loop. 我想运行一个while循环并读取整数,这样我将在循环的每次迭代后分别获得3,4,5,6,7,8和10。

This is really simple to do in C/C++ but not in Java... 这在C / C ++中很简单,但在Java中却不行......

I tried this code: 我试过这段代码:

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

    }

and what I get is: 而我得到的是:

51
540287029
540418080
538982176
151599117
171511050
218762506
825232650

How do I read the integers from this file in Java ? 如何从Java中读取此文件中的整数?

One can use the Scanner class and its nextInt method: 可以使用Scanner类及其nextInt方法:

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

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

Output: 输出:

3
4
5
6

Basically by default, the Scanner object will ignore any whitespace, and will get the next token. 基本上默认情况下, Scanner对象将忽略任何空格,并将获得下一个标记。

The Scanner class as a constructor which takes an InputStream as the source for the character stream, so one could use a FileInputStream that opens the source of the text. Scanner类作为构造函数 ,它将InputStream作为字符流的源,因此可以使用FileInputStream打开文本源。

Replace the Scanner instantiation in the above example with the following: 使用以下内容替换上例中的Scanner实例:

Scanner s = new Scanner(new FileInputStream(new File(filePath)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM