我有一个简单的输出文本文件,名为 logOutput.txt
:
2
3
4
我希望我的 Java 程序给出文件中最新的一个 ( 4 )。这是我的代码:
import java.util.*;
import java.io.*;
public class readLogFile {
public static void main(String[] a) {
int logNumber = 0;
try {
File file = new File("logOutput.txt");
Scanner input = new Scanner(file);
while (input.hasNext()) {
logNumber = input.nextInt();
}
System.out.println("the log # is: " + logNumber);
} catch (FileNotFoundException fne) {
}
}
}// end class
我主要关心的是 while 循环。有没有更高效的方法呢?在这里,我将每一行读入变量,然后覆盖它。我在想 - 也许要检查 nextInt
何时出现为空?
谢谢
最佳答案
您可以使用Integer.parse()
检查输入
在 while 循环中:
String s = input.nextLine();
try{
int i = Integer.parseInt(s);
logNumber = i;
} catch(NumberFormatException ex) {
System.out.println("It is not an int");
}
如果该行不是整数或空,将抛出异常。
关于java - Java中有没有更有效的方法从文件中读取数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31553225/