【问题标题】:Why won't this code display Error: Could not find file when e is thrown by a nonexistant file?为什么此代码不显示错误:当 e 被不存在的文件抛出时,找不到文件?
【发布时间】:2014-12-15 07:13:37
【问题描述】:

这是我的代码。当我给它一个不存在的文件名时,由于某种原因没有抛出 FileNotFoundException。

 public static String Question1( String fileName )
 {   
    String message = ""; 
    if ( fileName == null )
    {   
        fileName = "files/question1/sample.txt"; 
    }

    try
    {  

        Scanner fileScan = new Scanner( new File ( fileName ));

        while ( fileScan.hasNext() )
        {
            String readLine = fileScan.nextLine();

            if ( message.equals( "" ) )
            {
                message = readLine + "\n";
            }
            else
            {
                message = message + readLine + "\n";
            }
        }
    }

    catch ( FileNotFoundException e )
    {
        message = "Error: Could not find file!";
    }

    return message;
 }

当我使用不存在的文件名运行代码时,返回的消息是“”而不是“错误:找不到文件!”

【问题讨论】:

  • 你调试过代码,确定异常被捕获了吗?
  • 很明显文件确实存在。 很明显。

标签: java filenotfoundexception


【解决方案1】:

我称之为恶作剧 :-) 我怀疑文件 确实 存在于你的案例中,因为这段代码工作得很好:

import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;

public class Test {
    public static String Question1(String fileName) {   
        String message = "";
        if ( fileName == null )
            fileName = "files/question1/sample.txt"; 

        try {  
            Scanner fileScan = new Scanner(new File(fileName));
            while (fileScan.hasNext()) {
                String readLine = fileScan.nextLine();
                if (message.equals("")) {
                    message = readLine + "\n";
                } else {
                    message = message + readLine + "\n";
                }
            }
        } catch (FileNotFoundException e) {
            message = "Error: Could not find file!";
        }

        return message;
    }

    public static void main(String[] args) {
        System.out.println(Question1("no_such_file.txt"));
    }
}

按预期运行该输出:

Error: Could not find file!

当我创建该文件时,程序会输出其内容。

我建议再次查看您的文件系统,然后通过单步调试器运行您的代码以跟踪代码流。

【讨论】:

  • 你是对的。我将单元测试中的文件名从 blah.txt 更改为 blahlsdfjs.txt,现在它工作正常。谢谢。
【解决方案2】:

您确定抛出异常FileNotFoundException

可能发生的情况是在放置此类的相对路径中,您认为不存在的文件可能存在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-02
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多