1

我认为只显示代码和我得到的输出比试图解释它更容易:)

这是来自我的主要方法:

//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):

不存在.txt

java.lang.NullPointerException

请再试一次。

为什么 System.out.println(e) 会出现 NullPointerException?当我输入一个空文件或带有文本的文件时,它工作得很好。空文件打印 InvalidFileException(自定义异常)消息。

当我在“in = new Scanner(new File(filename));”周围放置一个 try-catch 语句并让 catch 块显示异常时,我确实打印出 FileNotFoundException,然后是 NullPointerException(我如果异常已经在 checkIfValid 方法中被捕获,不完全确定为什么 main 方法中的 catch 块会被激活......)。

我在这上面花了一段时间,我完全不知道出了什么问题。任何帮助,将不胜感激。谢谢!

4

2 回答 2

3

编辑:我认为空指针来自对 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;        
}
于 2012-12-03T02:22:02.090 回答
-1

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!

于 2012-12-03T03:40:50.947 回答