繁体   English   中英

从FileNotFoundException获取文件的文件名

[英]Get the filename of the file from FileNotFoundException

我想获取在Java应用程序中发生文件异常时不存在的文件的文件名,以便向用户发送一条简短消息。

catch (FileNotFoundException e) {
       /* what code to put here to get the filename of the file */
        }

这应该显示不存在的文件路径:

try {
    //access file
} catch(FileNotFoundException e) {
    System.out.println(e.getMessage());
}

输出,用于使用new Scanner(new File("C:/filetest"))创建一个Scanner

C:\\ filetest(系统找不到指定的文件)

除非您在catch块中解析了stacktrace,否则您将无法正确掌握文件名。

您可以将文件名存储在try块之外,即:

String filename = ...
try {
   // process file
} catch (FileNotFoundException e) {
    String message = String.format("The file % could not be found.", filename);
    // Show message to user
}

或者,您可以在尝试访问文件之前检查文件是否存在:

 File file = new File(filename);
 if (!file.exists()) {
      // Show error to user.
 }

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM