如何处理FileNotFoundException?

时间:2013-07-17 21:27:17

标签: java exception-handling filenotfoundexception

我正在修补一个小应用程序,从文件中读取一些数字。到目前为止一切运行良好,但现在我遇到了一个问题,我不知道如何有效地解决它。如果用户无意中输入了错误的文件名,JVM将抛出FileNotFoundException,这是我在调用方法中捕获的。现在我想给他(用户)另外两个尝试输入正确的文件名,但我不知道如何再次调用该方法,当我实际上在下面的catch块中时打开文件。 我将在下面说明我的瞬态解决方案,但我不确定这是否是解决此问题的最有效/最优雅的方法:

//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是一个扫描程序,它读取用户输入并将其分配给String变量文件名。 fileOpen是一个获取文件名,打开文件,读取内容并在向量中写入所有数字的方法。

所以,我非常感谢经验丰富的java程序员提供的所有支持。

问候 汤姆

6 个答案:

答案 0 :(得分:1)

你可以使用这样的东西,

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

答案 1 :(得分:1)

您可能希望以递归方式再次调用该方法:

  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;
      }
      // ...
  }

然后只需致电doTheStuff(3)

答案 2 :(得分:0)

您可以使用exists

File方法

例如,fileOpen方法可以返回true / false,无论文件是否存在

答案 3 :(得分:0)

认为这样可行。

    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++
    }

答案 4 :(得分:0)

这样的事情怎么样(伪代码,不可执行)?

// ...
    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;
    }
}

或者,在调用fileOpen()之前检查文件是否存在。

答案 5 :(得分:0)

不要使用例外来控制WorkFlow。尝试这样的事情:

 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
       }
     }
}
相关问题