0

几周前,我在这里发布了这个问题。现在我在不同的情况下遇到了类似的问题。我创建了一个 java 上传,我想在其中检查 XML 文件是否格式正确。检查后,我想删除它。但如果转换失败,我无法删除该文件。我创建了一个更简单的示例来在我遇到相同问题的本地计算机上运行它。请参阅下面的我的源代码。您可以轻松地复制和粘贴它并自己尝试。

我是否发现了一个错误,可能是我几周前报告的同一个错误,或者我错过了代码中的某些内容?我用的是撒克逊 9.4HE。

public class TestClass 
{
public static void main (String[] args) throws Exception
{
    boolean isWellFormed = isXMLwellformed(new File("work/file.xml"));

    if(isWellFormed) System.out.println("File is well formed");
    else
    {
        System.out.println("File is not well formed");
    }
    FileUtils.deleteDirectory(new File("work"));
}

private static boolean isXMLwellformed(File file)
{
    boolean isWellformed = true;
    TransformerFactory factory = TransformerFactory.newInstance();
    StreamSource source = new StreamSource(file);
    try 
    {
        Transformer trans = factory.newTransformer();
        SAXResult sink = new SAXResult(new DefaultHandler());
        trans.transform(source, sink);
    } 
    catch (TransformerException err) 
    {
        System.err.println("Validation failed: " + err.getMessage());
        isWellformed = false;
    }
    return isWellformed;
}
}
4

1 回答 1

1

现在,我找到了一个可行的解决方案。如果我自己创建 FileReader 并在 catch 块中关闭它,它就可以工作。但是不应该自动关闭吗?

    private static boolean isXMLwellformed(File file) throws IOException
   {
    boolean isWellformed = true;
    BufferedReader br = new BufferedReader(new FileReader(file));
    TransformerFactory factory = TransformerFactory.newInstance();
    StreamSource source = new StreamSource(br);
    try 
    {
        Transformer trans = factory.newTransformer();
        SAXResult sink = new SAXResult(new DefaultHandler());
        trans.transform(source, sink);
    } 
    catch (TransformerException err) 
    {
        System.err.println("Validation failed: " + err.getMessage());
        br.close();
        isWellformed = false;
    }
    return isWellformed;
    }
于 2013-08-20T14:56:11.380 回答