Java resource management: understanding Findbugs results

后端 未结 4 649
悲&欢浪女
悲&欢浪女 2021-01-06 19:09

Findbugs bugs me about a method which opens two Closeable instances, but I can\'t understand why.

Source

public static void sourceXmlT         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-06 19:15

    FindBugs is correct: If the FileWriter's constructor throws an exception, the file reader will not be closed. To verify this, try passing an invalid filename for output.

    I'd do it as follows:

        FileReader fileReader = new FileReader(input);
    
        try {
            FileWriter fileWriter = new FileWriter(output);
            try {
                // may throw something
                sourceXmlToBeautifiedXml(fileReader, fileWriter);
            } finally {
                fileWriter.close();
            }
        } finally {
            fileReader.close();
        }
    

    Note that the handling of exception thrown when closing could be improved, since leaving a finally-block by throwing an exception will cause the try-statement to terminate by throwing that exception, swallowing any exception thrown in the try-block, which generally would be more useful for debugging. See duffymo's answer for a simple way on how to avoid this.

    Edit: Since Java 7, we can use the try-with-resources statement, which permits correct and concicse handling of these corner cases:

    try (
        FileReader fileReader = new FileReader(input); 
        FileWriter fileWriter = new FileWriter(output)
    ) {
        // may throw something
        sourceXmlToBeautifiedXml(fileReader, fileWriter);
    }
    

提交回复
热议问题