简体   繁体   中英

Java.IO.FileNotFoundException Handling

When doing this, I am trying to make it "dummy proof" for my coworkers, so if they put in a file path instead of a file - the program doesn't stop so that they can just keep going in the application - it'll just ask them again. However currently

FileNotFoundException: C:\Users\usersname\Desktop\userImports\current (Access is denied)
java.io.FileNotFoundException: C:\Users\usersname\Desktop\userImports\current (Access is denied)

How do I work for this? I don't want it to crash like this, I'd rather it just say, "thats not a file - please try again"

How do I better handle file not found exceptions?

 File f;
            do {
                System.out.print("Please give me the " + type + "file: " );
                String file = console.nextLine();
                f = new File(file);
            } while (!f.exists());
            Scanner readMe = null;
            try {
                readMe = new Scanner(f);
            } catch (FileNotFoundException e) {
                System.err.println("FileNotFoundException: " + e.getMessage());
                e.printStackTrace();
            }
            return readMe;
        }

I'm not sure I understood what you exactly want but this is my answer to what I understood : Just loop while u don't find the file and you can also add a counter like after 5 times u exit the program.

File f;
boolean found = false ; 

  while (!found) {

        do {
            System.out.print("Please give me the " + type + "file: " );
            String file = console.nextLine();
            f = new File(file);
        } while (!f.exists());

        Scanner readMe = null;

        try {

            readMe = new Scanner(f);
            found = true ; 

        } catch (FileNotFoundException e) {
            found = false ; 
            System.err.println("FileNotFoundException: " + e.getMessage());

            system.out.printl  ( "A problem occured while loading the file please try again ");
            //e.printStackTrace();
        }
  }

  return readMe;

}

"Access is denied" means that the file does exist but the user who ran the program is not allowed to access - in your case read - it. It could be, ia, that the user does not have the necessary authority, or that the file is being held by another program.

Try to use canRead() instead of exists()

do {
  ...
} while (!f.canRead());

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