我认为仅显示代码和我得到的输出比尝试解释它更容易:)
这是我的主要方法:
//prompt user for filename
System.out.println("Please enter the text file name. (Example: file.txt):");
String filename = ""; //will be used to hold filename
//loop until user enters valid file name
valid = false;
while(!valid)
{
filename = in.next();
try
{
reader.checkIfValid(filename);
valid = true; //file exists and contains text
}
catch (Exception e)
{
System.out.println(e + "\nPlease try again.");
}
}
这是 reader.checkIfValid 方法:
public void checkIfValid(String filename) throws InvalidFileException, FileNotFoundException
{
try
{
in = new Scanner(new File(filename));
if (!in.hasNextLine()) // can't read first line
throw new InvalidFileException("File contains no readable text.");
}
finally
{
in.close();
}
}
这是输入不存在的文件时得到的输出:
请输入文本文件名。 (示例:file.txt):
doesNotExist.txt
java.lang.NullPointerException
请重试。
为什么 System.out.println(e) 会出现 NullPointerException?当我输入空文件或带有文本的文件时,它工作得很好。空文件打印 InvalidFileException(自定义异常)消息。
当我在“in = new Scanner(new File(filename));”周围放置一条 try-catch 语句,并让 catch block 显示异常时,我确实打印了 FileNotFoundException出,后跟 NullPointerException(我不完全确定如果 checkIfValid 方法已经捕获了异常,为什么会激活 main 方法中的 catch block ...)。
我已经花了一段时间在这上面,但我完全不知道出了什么问题。任何帮助,将不胜感激。谢谢!
最佳答案
编辑:我认为空指针来自对 reader 的调用,捕获所有异常是不好的做法,因为您不再知道它们来自哪里!
也许 checkIfValid 方法应该只检查文件名是否有效?
public boolean checkIfValid(String filename) {
try {
File file = new File(filename);
return file.exists();
} catch (FileNotFoundException) {
System.out.println("Invalid filename ["+filename+"] "+e);
}
}
然后调用它的代码可能看起来像;
filename = in.next();
valid = reader.checkIfValid(filename);
if (valid)
List<String> fileContents = readFromFile(filename);
然后将所有文件读取逻辑包含在它自己的方法中,如下所示;
public List<String> readFromFile(filename) {
List<String> fileContents = new ArrayList<String>();
try {
in = new Scanner(new File(filename));
while (in.hasNextLine()) {
fileContents.add(in.nextLine);
}
} catch (IOException e){
//do something with the exception
} finally {
in.close();
}
return fileContents;
}
关于java - 在 Java 中,为什么在尝试显示 FileNotFoundException 时会收到 NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13676228/