2017-08-17 63 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()); 
相關問題