2013-02-11 76 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中:如果它不存在,请放置要运行的代码。