假设我的输入文件包含:
3 4 5 6 7 8
9
10
Run Code Online (Sandbox Code Playgroud)
我想运行一个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) {
}
Run Code Online (Sandbox Code Playgroud)
而我得到的是:
51
540287029
540418080
538982176
151599117
171511050
218762506
825232650
Run Code Online (Sandbox Code Playgroud)
如何从Java中读取此文件中的整数?
coo*_*ird 15
Scanner s = new Scanner("3 4 5 6");
while (s.hasNext()) {
System.out.println(s.nextInt());
}
Run Code Online (Sandbox Code Playgroud)
输出:
3
4
5
6
Run Code Online (Sandbox Code Playgroud)
基本上默认情况下,Scanner
对象将忽略任何空格,并将获得下一个标记.
Scanner
作为构造函数的类,它将InputStream
字符串作为源的源,因此可以使用FileInputStream
打开文本源的构造函数.
使用Scanner
以下内容替换上例中的实例化:
Scanner s = new Scanner(new FileInputStream(new File(filePath)));
Run Code Online (Sandbox Code Playgroud)