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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1414444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 16:28:15  来源:igfitidea点击:

How do I read formatted input in Java?

javainputio

提问by Lazer

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 filein Java?

如何在Java 中从此文件中读取整数?

回答by coobird

One can use the Scannerclass and its nextIntmethod:

可以使用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 Scannerobject will ignore any whitespace, and will get the next token.

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

The Scannerclass as a constructorwhich takes an InputStreamas the source for the character stream, so one could use a FileInputStreamthat opens the source of the text.

Scanner班作为构造这需要一个InputStream作为源字符流,所以人们可以使用FileInputStream打开的文本的来源。

Replace the Scannerinstantiation in the above example with the following:

Scanner上面示例中的实例化替换为以下内容:

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