2017-08-17 41 views
0

当我这样做时,我试图让它成为我的同事的“假证明”,所以如果他们放入文件路径而不是文件 - 程序不会停下来,以便他们可以只要继续申请 - 它会再次问他们。但目前Java.IO.FileNotFoundException处理

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

我该如何工作?我不希望它像这样崩溃,我宁愿它只是说,“那不是一个文件 - 请再试一次”

如何更好地处理文件没有发现异常?

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; 
     } 
+1

*你*打印您'catch'块内的堆栈跟踪。相反,你可以打印任何你想要的信息。 – khelwood

+0

您可以使用[File](https://docs.oracle.com/javase/7/docs/api/java/io/File.html)类。它有几个选项,你可能正在寻找,如[文件存在](https://docs.oracle.com/javase/7/docs/api/java/io/File.html#exists()), [文件#isFile](https://docs.oracle.com/javase/7/docs/api/java/io/File.html#isFile())或[File#canWrite](https://docs.oracle。 com/javase/7/docs/api/java/io/File.html#canWrite()) – SomeJavaGuy

+0

如果我们提供任何不允许从外部程序访问的文件,则可能出现“访问被拒绝”。确保ani-one可以访问该文件 –

回答

2

我不知道我理解你到底想要什么,但,这是我的回答对我的理解: 只是循环,当你不找到该文件,你也可以添加一个计数器等之后,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; 

} 
0

“访问被拒绝”意味着该文件确实存在,但谁运行该程序的用户不允许访问 - 在你的情况看 - 它。它可能是,即用户没有必要的权限,或者该文件被另一个程序持有。

0

尝试使用的CanRead(),而存在()

do { 
    ... 
} while (!f.canRead()); 
相关问题