简体   繁体   中英

Get the filename of the file from FileNotFoundException

I want to get the filename of the file that do not exist when a file exception occur in my java application so that i can give a short message to the user.

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

This should display the non-existing file path:

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

Output, for creating a Scanner with new Scanner(new File("C:/filetest")) :

C:\\filetest (The system cannot find the file specified)

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

You can either store the filename outside of the try block, ie:

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

Or you can check whether the file exists before trying to access it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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