Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用java文件I/O正确捕获异常_Java - Fatal编程技术网

如何使用java文件I/O正确捕获异常

如何使用java文件I/O正确捕获异常,java,Java,我正在努力熟悉Java中的文件I/O。我一开始在编译时遇到很多错误,比如error:unreportedexception;必须捕获或声明要抛出。因此,我对代码进行了一些更改,最终得到: public static void main(String[] args){ FileInputStream in = null; FileOutputStream out = null; String content = "hello"; byte[] contentByte

我正在努力熟悉Java中的文件I/O。我一开始在编译时遇到很多错误,比如
error:unreportedexception;必须捕获或声明要抛出
。因此,我对代码进行了一些更改,最终得到:

public static void main(String[] args){
    FileInputStream in = null;
    FileOutputStream out = null;
    String content = "hello";
    byte[] contentBytes = content.getBytes();

    try{
        out = new FileOutputStream("output.txt");
        out.write(contentBytes);
    }catch(IOException e){

    }catch(FileNotFoundException e){

    }
    finally{
        if (out != null)
            out.close();
    }
}
不过,我还是发现了这个错误:

FileIO.java:16: error: exception FileNotFoundException has already been caught
        }catch(FileNotFoundException e){
         ^
FileIO.java:21: error: unreported exception IOException; must be caught or declared to be thrown
                out.close();
                         ^
2 errors
  • 我在哪里“已经捕获”了FileNotFoundException
  • 由于第二个错误,我是否需要在
    finally
    子句中放置另一个
    try
    catch
    语句来捕获
    IOException
    ?这看起来既混乱又过于复杂。我做错什么了吗?为什么java不让我做我想做的事情而不强迫我捕获异常
  • 编辑:

    如果我这样做:

    public static void main(String[] args){
        FileOutputStream out = null;
        String content = "hello";
        byte[] contentBytes = content.getBytes();
    
        try{
            out = new FileOutputStream("output.txt");
            out.write(contentBytes);
        }catch(FileNotFoundException e){
    
        }catch(IOException e){
    
        }
        finally{
                if (out != null)
                out.close();
    
        }
    }
    
    我得到:

    FileIO.java:20: error: unreported exception IOException; must be caught or declared to be thrown
                    out.close();
                             ^
    1 error
    

    由于
    FileNotFoundException
    扩展了
    IOException
    ,因此只需捕获
    IOException
    即可捕获
    IOException
    的所有子类型

    And regarding your second question, since `.close()` method also throws `IOException`, you can put all the IO code in a method, and have that method to throw `IOException`, then the caller can deal with the any exceptions.
    
    for example:
    
    private static void writeToFile() throws IOException{
     FileInputStream in = null;
        FileOutputStream out = null;
        String content = "hello";
        byte[] contentBytes = content.getBytes();
        try{
            out = new FileOutputStream("output.txt");
            out.write(contentBytes);
        }finally{
            if (out != null)
                out.close();
        }
    }
    
    然后你的主屏幕就会像这样

    public static void main(String[] args){
        FileInputStream in = null;
        FileOutputStream out = null;
        String content = "hello";
        byte[] contentBytes = content.getBytes();
    
        try{
           writeToFile();
        }catch(IOException e){
    
        }
    }
    
    看看

    我在哪里“已经捕获”了FileNotFoundException

    扩展
    IOException
    ,这意味着IOException可以捕获
    FileNotFoundException
    异常。因此,在它之后没有
    FileNotFoundException
    的意义

    只要颠倒顺序,就可以解决这个问题

    }catch(FileNotFoundException e){
    
    }catch(IOException e){
    
    }
    
    另外,不要将catch块留空,使用它们来显示适当的消息,否则,如果出现任何异常,您将不会有任何线索

    第二个错误,我是否需要在finally子句中放入另一个try-and-catch语句来捕获IOException

    对。但是,我建议使用它,因为它最终会关闭资源


    如前所述,您应该使用


    我真的不确定编译器是如何让你理解代码的。你能试试下面的代码吗。我运行它时没有任何错误

    第一个问题的答案是:

    删除FileNotFoundException行或将其置于IOexception之上

    第二个问题的答案是:

    如果您认为这很混乱,可以使用Throws来回避异常,即在main(String[]args)旁边抛出IOException

    Java(编译器)促使您捕获或声明异常(使用抛出),因为Java中异常的主要目的不是在代码运行时出错。当finally块中发生异常时,它会导致错误,并最终在运行时影响应用程序。当你在最后一个街区关东西的时候必须非常小心。如果您认为代码看起来很凌乱,那么您可以使用Throws关键字来解决您的问题

        public static void main(String[] args){
            FileInputStream in = null;
            FileOutputStream out = null;
            String content = "hello";
            byte[] contentBytes = content.getBytes();
    
            try{
                out = new FileOutputStream("output.txt");
                out.write(contentBytes);
            }catch(IOException e){
    
            }
            finally{
                if (out != null){
        try{
                    out.close();
        }catch(IOException e){
    
        }
        }
            }
        }
    
    }

    正如QuakeCore提到的扩展IOException,这就是为什么您应该首先捕获FileNotFoundEception

    最好至少打印一些消息,这样当控制台/日志中没有输出和异常时,您不会感到惊讶



    实现自动关闭接口。这就是为什么使用它更好的原因。在这种情况下,JVM将自动关闭它

    谢谢。问题2呢?谢谢。“第二个问题呢?”萨汉德已经回答了。如果您有任何具体问题,请告诉我。事实并非如此,同样的错误仍然存在于您的解决方案中。@sah我注意到很多次,您似乎有立即投反对票的习惯。你们应该有耐心,反反复复地问问题。@sah和Yes。它只负责关闭资源,否则与旧版本相同。但是为什么我们需要这么多的尝试和捕捉呢?嗨@Sahand,我已经按照你的要求更新了帖子。请过目一下。谢谢你的投票。快乐编码!!谢谢但似乎存在格式错误。您好,答案本身中的哪一行?这有什么意义?FileNotFoundException单独捕获IOException?异常可以是IOException或FileNotFoundException,在这两种情况下,catch子句都将捕获它。您的另一个问题可能在此处得到回答:。尽管我建议每篇文章坚持一个问题,以获得每个问题的更好答案,并使文章对其他人更有用。@Ravi这篇文章目前提出了两个不同的问题-可能需要对问题主体(作者)进行相当重要的编辑,以证明标题只关注其中一个问题是合理的(尽管答案会使这样的编辑产生问题).@Dukeling你是在建议我退后一步吗?@Ravi,如果你愿意的话。虽然我不太介意,因为我认为这个问题应该以过于宽泛或重复的形式结束。@Dukeling我退后一步。我想让标题更有意义,以便人们可以轻松搜索。但是,我同意你的观点。:-)
        public static void main(String[] args){
            FileInputStream in = null;
            FileOutputStream out = null;
            String content = "hello";
            byte[] contentBytes = content.getBytes();
    
            try{
                out = new FileOutputStream("output.txt");
                out.write(contentBytes);
            }catch(IOException e){
    
            }
            finally{
                if (out != null){
        try{
                    out.close();
        }catch(IOException e){
    
        }
        }
            }
        }
    
    public static void main(String[] args) throws IOException{
    FileOutputStream out = null;
    String content = "hello";
    byte[] contentBytes = content.getBytes();
    
    try{
        out = new FileOutputStream("output.txt");
        out.write(contentBytes);
    }catch(FileNotFoundException e){
    
    }
    finally{
            if (out != null)
            out.close();
    
    }
    
    String outputPath = "output.txt";
    String content = "hello";
    byte[] contentBytes = content.getBytes();
    try (FileOutputStream out = new FileOutputStream(outputPath)) {
        out.write(contentBytes);
    } catch (FileNotFoundException e) {
        System.err.println("Failed to find the file to write to: " + outputPath);
    } catch (IOException e) {
        System.err.println("Failed to write to file: " + outputPath);
    }