简体   繁体   English

如何处理FileNotFoundException?

[英]How to handle a FileNotFoundException?

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. 如果用户无意中输入了错误的文件名,JVM将抛出FileNotFoundException,这是我在调用方法中捕获的。 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. 现在我想给他(用户)另外两个尝试输入正确的文件名,但我不知道如何再次调用该方法,当我实际上在下面的catch块中时打开文件。 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. input是一个扫描程序,它读取用户输入并将其分配给String变量文件名。 fileOpen is a method which takes a filename, opens the file, reads the content and write all numbers in a vector. fileOpen是一个获取文件名,打开文件,读取内容并在向量中写入所有数字的方法。

So, I would really appreciate every support from the more experienced java programmers. 所以,我非常感谢来自经验丰富的java程序员的所有支持。

Greetings Tom 问候汤姆

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

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) 然后简单地调用doTheStuff(3)

You can use exists method of the File class 您可以使用File类的exists方法

For example fileOpen method can return true/false whether file exists 例如, fileOpen方法可以返回true / false,无论文件是否存在

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

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(). 或者,在调用fileOpen()之前检查文件是否存在。

Do not use exceptions to control your WorkFlow. 不要使用例外来控制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
       }
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何处理此FileNotFoundException? - How do I handle this FileNotFoundException? 如何在Mule中扩展AbstractMessageTransformer的Java类中处理FileNotFoundException? - How to handle FileNotFoundException in Java class extending AbstractMessageTransformer in Mule? 正确处理FileNotFoundException Java的方法 - Proper way to handle filenotfoundexception Java 如何在android中从webservice加载图像时处理java.io.FileNotFoundException - How to handle java.io.FileNotFoundException while loading images from webservice in android 如何修复FileNotFoundException? - How to fix FileNotFoundException? 如何修复 FileNotFoundException? - How to fix a FileNotFoundException? 如何处理此错误IOFiles模块:不存储加密的数据,发生IO错误:java.io.FileNotFoundException(访问被拒绝? - How to handle this error IOFiles MODULE: Encryped data don't stored, an IO error ocurred:java.io.FileNotFoundException (access is denied? 如何为新的ClassPathXmlApplicationContext()捕获FileNotFoundException - How to catch FileNotFoundException for new ClassPathXmlApplicationContext() 如何为此“ FileNotFoundException”编写Junit测试 - How to write Junit test for this “FileNotFoundException” 如何捕获两个文件的FileNotFoundException? - How to catch FileNotFoundException for two files?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM