简体   繁体   English

Java.IO.FileNotFoundException处理

[英]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. 我不确定我是否了解您的确切需求,但这是我对我所了解的答案:只是在您找不到文件时循环,您还可以添加计数器,例如在退出程序5次之后。

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() 尝试使用canRead()而不是exist()

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

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

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