简体   繁体   English

在 Java 中,为什么我在尝试显示 FileNotFoundException 时会收到 NullPointerException?

[英]In Java, why am I getting a NullPointerException when trying to display a FileNotFoundException?

I think it's easier to just show the code and the output I'm getting than trying to explain it :)我认为只显示代码和我得到的输出比试图解释它更容易:)

This is from my main method:这是来自我的主要方法:

//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.");
        }
    }

And this is the reader.checkIfValid method:这是 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();
    }
}

This is the output I get when a nonexistent file is entered:这是输入不存在的文件时得到的输出:

Please enter the text file name.请输入文本文件名。 (Example: file.txt): (例如:file.txt):

doesNotExist.txt不存在.txt

java.lang.NullPointerException java.lang.NullPointerException

Please try again.请再试一次。

Why is the System.out.println(e) getting a NullPointerException?为什么 System.out.println(e) 得到 NullPointerException? When I enter an empty file or a file with text, it works just fine.当我输入一个空文件或一个带有文本的文件时,它工作得很好。 The empty file prints the InvalidFileException (a custom exception) message.空文件打印 InvalidFileException(自定义异常)消息。

When I put a try-catch statement around the "in = new Scanner(new File(filename));", and have the catch block display the exception, I do get the FileNotFoundException printed out, followed by the NullPointerException (I'm not entirely sure why the catch block in the main method would be activated if the exception was already caught in the checkIfValid method...).当我在“in = new Scanner(new File(filename));”周围放置一个 try-catch 语句,并让 catch 块显示异常时,我确实打印出了 FileNotFoundException,然后是 NullPointerException(我是如果异常已经在 checkIfValid 方法中被捕获,不完全确定为什么主方法中的 catch 块会被激活......)。

I've spent a while on this and I'm completely clueless as to what's wrong.我在这上面花了一段时间,我完全不知道出了什么问题。 Any help would be appreciated.任何帮助,将不胜感激。 Thanks!谢谢!

edited: I think the null pointer comes from the call to reader, it is poor practise to catch all exceptions as you no longer know where they came from!编辑:我认为空指针来自对读者的调用,捕获所有异常是不好的做法,因为您不再知道它们来自哪里!

Maybe the checkIfValid method should just check if the filename is valid?也许 checkIfValid 方法应该只检查文件名是否有效?

public boolean checkIfValid(String filename) {
    try {
        File file = new File(filename);
        return file.exists();   
    } catch (FileNotFoundException) {
        System.out.println("Invalid filename ["+filename+"] "+e);
    }
}

Then the code calling it could look like;然后调用它的代码可能看起来像;

filename = in.next();
valid = reader.checkIfValid(filename);
if (valid)
    List<String> fileContents = readFromFile(filename);

Then contain all the file reading logic in it's own method like this;然后像这样在它自己的方法中包含所有文件读取逻辑;

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;        
}

My mistake was something only I could've seen.我的错误只有我才能看到。 I was catching all the exceptions so I wasn't able to see where it was coming from.我正在捕获所有异常,所以我无法看到它来自哪里。 Thank you for helping!感谢您的帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在尝试将实体保存到列表时会收到 NullPointerException? - Why am i getting a NullPointerException when trying to save an entity to a list? 为什么我在尝试读取文件时收到 NullPointerException? - Why am I getting a NullPointerException when trying to read a file? 为什么在尝试填充数组时会出现NullPointerException? - Why, when trying to populate an array, am I getting a NullPointerException? Why am I getting a java.io.FileNotFoundException: http://10.0.2.2:4000/products/add when trying to send http request? - Why am I getting a java.io.FileNotFoundException: http://10.0.2.2:4000/products/add when trying to send http request? 为什么我会收到 FileNotFoundException? - Why am I getting a FileNotFoundException? 为什么在Java中使用数组获取NullPointerException? - Why am I getting a NullPointerException with arrays in Java? 如果我要读取的文件与我正在使用的Java文件位于同一软件包中,为什么我仍然收到“ FileNotFoundException”? - If the file I am trying to read is in the same package as the java file I'm working with, why am I still getting a “FileNotFoundException”? 为什么在此程序中出现java.io.FileNotFoundException? - Why am I getting java.io.FileNotFoundException in this program? 为什么在击中URL来获取内容时出现FileNotFoundException? - Why am I getting FileNotFoundException when hitting a URL to fetch content? 为什么我收到NullPointerException却不显示添加的组件? - Why am I getting a NullPointerException and no display the component i added?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM