错误:线程“中出现异常”;“主要”;java.lang.NullPointerException
readfile类是我创建的一个类,因此我可以从file.txt读取一些字符串,然后在控制台中打印它们:错误:线程“中出现异常”;“主要”;java.lang.NullPointerException,java,Java,readfile类是我创建的一个类,因此我可以从file.txt读取一些字符串,然后在控制台中打印它们: package mainpackage; import java.io.*; import java.util.*; public class readfile { private Scanner x; public void openFile(){ try { x = new Scanner(new Fil
package mainpackage;
import java.io.*;
import java.util.*;
public class readfile {
private Scanner x;
public void openFile(){
try {
x = new Scanner(new File("file.txt"));
} catch (Exception e) {
System.out.println("Could not find file");
}
}
public void readFile(){
while(x.hasNext()){
System.out.print(x.nextLine()+"\n");
}
}
public void closeFile(){
x.close();
}
}
但是,当我主要调用类的方法时,我会得到如下错误:
线程“main”java.lang.NullPointerException中出现异常。这是主呼叫:
public static void main(String [] args)
{
readfile r = new readfile();
r.openFile();
r.readFile();
r.closeFile();
}
有什么想法吗?谢谢您不应该在
openFile()
中捕获异常,或者如果捕获到异常,如果在openFile()中获得异常,则抛出新异常。
方法扫描程序将为空,而在其他方法中获得空指针异常
package mainpackage;
import java.io.*;
import java.util.*;
public class readfile {
private Scanner x;
public void openFile() throws Exception{
try {
x = new Scanner(new File("file.txt"));
} catch (Exception e) {
//in here throw (this/another) exception to caller or don't catch this exption
System.out.println("Could not find file");
throw new Exception("Could not find file");
}
}
public void readFile(){
while(x.hasNext()){
System.out.print(x.nextLine()+"\n");
}
}
public void closeFile(){
x.close();
}
}
和测试的主要驱动程序:
public static void main(String [] args)
{
try {
readfile r = new readfile();
r.openFile();
r.readFile();
r.closeFile();
} catch (Exception e) {
e.printStackTrace();
System.out.println("got exception");
}
}
若抛出异常,“x”下的值是多少? 接下来发生了什么
(应该使用调试器检查readFile()func)
我需要澄清:为了让@Marios p坐起来思考,我们提出了一些问题。除了例外,您的控制台输出是否出现“找不到文件”的情况?是的,很抱歉,我也忘了。它说在mainpackage.readfile.readfile.mainpackage.CreateUsers.mainWell的线程“main”java.lang.NullPointerException中找不到文件,然后出现异常。我现在懒得写答案,不想写在注释中,但只要想一想,你自己可能会想出一个;)(我也相信其他人很快就会告诉你)。让我们假设例外情况的存在是有原因的(主要是)事实上,我在这件事上纠缠了好几个小时,所以如果你有什么想法,你能给我一个提示吗?@MariosP你已经有了问题解决方案的答案。那你为什么问
下的值是多少。为什么这是一个答案呢?没有任何贡献,应该是一个注释。我使用你的代码,当我运行它时,类型得到异常,但我的记事本不是空的。我是java新手,我想我错过了一些简单的东西,但我仍然找不到它。现在你应该会收到“找不到文件”消息的异常,这意味着文件不存在@MariosPIt有两条消息:找不到文件exception@MariosP现在这意味着文件不存在,或者不在适当的位置。我的项目的bin文件夹中有一个file.txt文件。找不到它有什么问题,我收到了这个错误消息