-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);

How can I do an error check if the user enters a wrong file destination?

I get:

    java.io.FileNotFoundException:

when a invalid file destination is entered.

I want the program to say something like

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

I get errors for the methods isDirectory() and exists() telling me they don't exist for the type String when I try:

if (word.exists())
{
  //do blah blah
}
else 
{
  //Print error
}
Adz
  • 2,809
  • 10
  • 43
  • 61
  • 2
    `if (new File(word).exists())` – nhahtdh Feb 11 '13 at 17:07
  • Possible Duplicate: http://stackoverflow.com/questions/1816673/how-do-i-check-if-a-file-exists-java-on-windows – Pat Burke Feb 11 '13 at 17:08
  • Learn to use [try/catch](http://docs.oracle.com/javase/tutorial/essential/exceptions/try.html) and [exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) in general (learn how to read them) – ThanksForAllTheFish Feb 11 '13 at 17:09

2 Answers2

6

Wrap your word in File and then do the checks:

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

Alternatively, you may catch an exception when it is thrown:

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
}
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
0

Create a File instance of 'word' then check if it exists. For the exception, surround it with a try and catch, in the catch: put the code you want to run should it not exist.