2013-02-11 78 views
-1
Scanner user = new Scanner(System.in); 
    String word; 

    System.out.println("Location of file: "); 
    word = user.nextLine(); 

    FileReader fileOpen = new FileReader(word); 
    BufferedReader fileRead = new BufferedReader(fileOpen); 

如何在用戶輸入錯誤的文件目的地時進行錯誤檢查?Java中的文件目標無效?

我得到:當進入

java.io.FileNotFoundException: 

一個無效的文件目的地。

我希望該計劃說類似

System.out.println("Invalid directory"); 

我得到的錯誤的方法的isdirectory()和存在()告訴我,他們沒有爲String類型存在,當我嘗試:

if (word.exists()) 
{ 
    //do blah blah 
} 
else 
{ 
    //Print error 
} 
+2

'if(new File(word).exists())' – nhahtdh 2013-02-11 17:07:47

+0

可能重複:http://stackoverflow.com/questions/1816673/how-do-i-check-if-a-file-exists-java -Windows – 2013-02-11 17:08:44

+0

學習使用[try/catch](http://docs.oracle.com/javase/tutorial/essential/exceptions/try.html)和[例外](http://docs.oracle.com /javase/tutorial/essential/exceptions/index.html)一般(學習如何閱讀) – ThanksForAllTheFish 2013-02-11 17:09:17

回答

6

環繞你的文件單詞,然後做檢查:

if (new File(word).exists()) 
{ 
    //do blah blah 
} 
else 
{ 
    //Print error 
} 

或者,您也可以捕獲一個拋出時例外:

Scanner user = new Scanner(System.in); 
String word; 

System.out.println("Location of file: "); 
word = user.nextLine(); 

try { 
    FileReader fileOpen = new FileReader(word); 
    BufferedReader fileRead = new BufferedReader(fileOpen); 
} catch (FileNotFoundException fnf) { 
    // print an error 
} 
0

創建'word'文件實例,然後檢查它是否存在。對於例外情況,請在catch中將它包含在try和catch中:如果它不存在,請放置要運行的代碼。