0

I'm tinkering around on a small application to read some numbers in from a file. Everything runs well so far, but now I have encountered a problem I don't know how I can effectively fix it. If the user enters, unintentionally maybe, the wrong filename a FileNotFoundException will be thrown by the JVM, that I catch in my invoking method. Now I want to give him (the user) two another tries to enter the correct filename, but I don't know how I can invoke the method again which is opening the file when I'm actually in the catch-block below. I will illustrate my transient solution below, but I'm not really sure if this is the most effective/elegant way to solve this problem:

//code omitted
            int temp = 0;

        while(true) {
            filename = input.next();

            try {
                ex.fileOpen(filename);
            }
            catch(FileNotFoundException e) {
                if(temp++ == 3) {
                    System.err.println("You have entered the filename three times consecutively wrongly");
                    return;
                }
                continue;
            }
            break;
        }
//do some other stuff

input is a scanner which reads the user input and assigns it to the String-variable filename. fileOpen is a method which takes a filename, opens the file, reads the content and write all numbers in a vector.

So, I would really appreciate every support from the more experienced java programmers.

Greetings Tom

tzwickl
  • 1,341
  • 2
  • 15
  • 31
  • Check this link, it shows how to check if file exists http://stackoverflow.com/questions/1816673/how-do-i-check-if-a-file-exists-java-on-windows – Tiago Almeida Jul 17 '13 at 21:31
  • The exception is thrown by the JVM, not by the compiler. Precision please. @TiagoAlmeida He already has a foolproof way of checking that the file exists. The stuff in that link is 100% redundant given that FileNotFoundException is thrown. – user207421 Jul 17 '13 at 21:58
  • @EJP Thank you for the hint. I will try to be more precise the next time ;) – tzwickl Jul 17 '13 at 22:36

6 Answers6

1

You could use something like this,

public class AppMain {

  public static void main(String[] args) throws IOException {
    String filePath = input.next();

    InputStream is = getInputStream(filePath);
    int temp = 0;

    while(is == null && temp < 3){
      filePath = input.next();
      is = getInputStream(filePath);
      temp++;
    }

    if(is == null){
      System.err.println("You have entered the filename three times consecutively wrongly");
      return;
    }

    .........
    .........

  }

  private static InputStream getInputStream(String filePath){
    InputStream is = null;

    try{
      is = new FileInputStream(filePath);
      return is;
    }catch (IOException ioException) {
      return null;
    }
  }
}
  • nice solution. exactly for something like this I was looking for. To make a private method who checks if the file has been successfully opened or not :) It just didn't cross my mind ... – tzwickl Jul 17 '13 at 22:00
1

You may want to recursively call the method again:

  public void doTheStuff(int attemptsLeft)
      // ...
      if (attemptsLeft == 0) {
         System.err.println("You have entered the filename three times consecutively wrongly");
         return;
      }
      filename = input.next();
      try {
          ex.fileOpen(filename);
      }
      catch(FileNotFoundException e) {
          doTheStuff(attemptsLeft - 1);
          return;
      }
      // ...
  }

then simply call doTheStuff(3)

Jiri Kremser
  • 12,471
  • 7
  • 45
  • 72
  • Nice idea, but I'm not sure if this will actually work so? I mean after you have reached the return statement the program will jump back into the catch handler, and I think then it will just continue executing the program after the catch statement ... The program will then work with a not opened file. – tzwickl Jul 17 '13 at 22:05
0

You can use exists method of the File class

For example fileOpen method can return true/false whether file exists

Anton
  • 5,831
  • 3
  • 35
  • 45
0

Think this will work.

    int x = 0;
    while (true){
       filename = input.next();

       try{
          ex.fileOpen(filename);
          break;  // If it throws an exeption, will miss the break
       }catch(FileNotFoundException e){
          System.err.println("File not found, try again.");  
       }
       if (x==2){
          System.errprintln("You have entered the wrong file 3 times");
          System.exit(0);
       }
       x++
    }
Scott Allen
  • 513
  • 2
  • 13
0

How about something like this (pseudocode, not executable)?

// ...
    for(int i = 0; i < 3; i++)
    {
        // User interaction to get the filename

        if(attemptToOpenFile(ex))
        {
            break;
        }
    }
    // Check if the file is open here and handle appropriately.
// ...
}

bool attemptToOpenFile(File ex, String filename) { // Forgot the class name for this
    try {
        ex.fileOpen(filename);
        return true;
    } catch(FileNotFoundException e) {
        return false;
    }
}

Alternatively, check if the file exists before calling fileOpen().

confusopoly
  • 1,245
  • 7
  • 19
0

Do not use exceptions to control your WorkFlow. Try something like this:

 final int MAX_ERROR_ALLOWED=3;
public void readFile(String filename, int errorCount){
     try{
       File f = new File(filename);
       if(!f.exists()){
          String newFilename = input.next();
          if(errorCount>=MAX_ERROR_ALLOWED){
              throw new JustMyException();
          }
          readFile(newFilename, errorCount++);   
       }else{
           //whatever you need to do with your file
       }
     }
}
Ricardo Mogg
  • 589
  • 6
  • 18