Java resource management: understanding Findbugs results

后端 未结 4 622
悲&欢浪女
悲&欢浪女 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:36

    i'd say it's you.

    i'd close both resources in a separate try/catch block. i'd create static methods to help me:

    public static void sourceXmlToBeautifiedXml(File input, File output)
            throws TransformerException, IOException, JAXBException {
    
        FileReader fileReader = new FileReader(input);
        FileWriter fileWriter = new FileWriter(output);
    
        try {
            // may throw something
            sourceXmlToBeautifiedXml(fileReader, fileWriter);
        } finally {
            close(fileReader);
            close(fileWriter);
        }
    }
    
    
    // same for reader & writer
    public static void close(InputStream s)
    {
        try
        { 
           if (s != null)
           {
               s.close();
           }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    

提交回复
热议问题