Java 尝试使用扫描仪从文件中读取int时出现NullPointerException
我正试图从文件中读取信息。文件中的第一件事是一个整数,但当我尝试读取它时,会得到一个NullPointerException。我还尝试将文件中的第一个内容作为字符串读取,再次得到一个NullPointerException。然后,我在连接文件时添加了catch语句中的print语句。当我运行代码时,将对print语句求值。我的问题的根源是什么?谢谢Java 尝试使用扫描仪从文件中读取int时出现NullPointerException,java,nullpointerexception,java.util.scanner,Java,Nullpointerexception,Java.util.scanner,我正试图从文件中读取信息。文件中的第一件事是一个整数,但当我尝试读取它时,会得到一个NullPointerException。我还尝试将文件中的第一个内容作为字符串读取,再次得到一个NullPointerException。然后,我在连接文件时添加了catch语句中的print语句。当我运行代码时,将对print语句求值。我的问题的根源是什么?谢谢 private boolean collectSystem(String loc) { Scanner fileIn = null;
private boolean collectSystem(String loc) {
Scanner fileIn = null;
try {
fileIn = new Scanner(new File(loc));
} catch (FileNotFoundException e) {
System.out.println("File not found, IntakeSystem");
}
// Determine number of equations
try {
n = fileIn.nextInt();
} catch (InputMismatchException e) {
return false;
}
// Collect the text in the file as a string
String info = "";
while (fileIn.hasNextLine()) {
info = info + fileIn.nextLine();
}
fileIn.close();
//Separate equations in file
String[] eqns = new String[n];
int start = 0;
int end = info.indexOf(";");
for (int i = 0; i < n; i++) {
if(end == -1) return false;
String nextLine = info.substring(start, end);
eqns[i] = nextLine;
start = end + 1;
end = info.indexOf(";", start);
}
for (int i = 0; i < n; i++) {
System.out.println(eqns[n]);
}
return true;
}
专用布尔集合系统(字符串loc){
Scanner fileIn=null;
试一试{
fileIn=新扫描仪(新文件(loc));
}catch(filenotfounde异常){
System.out.println(“未找到文件,IntakeSystem”);
}
//确定方程式的数目
试一试{
n=fileIn.nextInt();
}捕获(输入不匹配异常e){
返回false;
}
//将文件中的文本收集为字符串
字符串信息=”;
while(fileIn.hasNextLine()){
info=info+fileIn.nextLine();
}
fileIn.close();
//将方程分开归档
字符串[]eqns=新字符串[n];
int start=0;
int end=info.indexOf(“;”);
对于(int i=0;i
从注释中可以看出,您传递的路径指向一个不存在的文件,请确保您首先实际传递的是一个有效的文件路径
使调试更容易的一种方法:
替换
System.out.println(“未找到文件,IntakeSystem”)在第一个catch块中,使用抛出新的IllegalArguementException(e)
或返回false
,因为否则,如果String loc
参数不指向现有文件,文件对象仍将为null,执行将继续;通过OP注释,这是您的问题。您能在代码中标记您获得NPE的确切位置吗?我怀疑您的代码抛出了一个FileNotFoundException
,但由于您只是吞下了异常(并将其打印出来),因此代码会转到fileIn.nextInt()
并在
中的文件上抛出一个NPE。在catch block.File中开发时使用e.printStackTrace()
,在IntakeSystem.collectSystem(IntakeSystem.java:37)的线程“main”中找不到IntakeSystem异常,在IntakeSystem.main(IntakeSystem.java:70)中使用IntakeSystem异常现在你知道原因了fileIn
对象为空。谢谢,这让我走上了正确的道路。由于某种原因,它无法识别富文本文件。我必须转换成纯文本文件,然后就没有问题了。再次感谢