gpt4 book ai didi

java - Saxon XML 验证 : Cannot delete XML File, 验证失败时

转载 作者:行者123 更新时间:2023-12-01 14:13:08 24 4
gpt4 key购买 nike

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

我是否发现了一个错误,也许是我几周前报告的同一个错误,或者我是否遗漏了代码中的某些内容?我用的是 Saxon 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;
}
}

最佳答案

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

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

关于java - Saxon XML 验证 : Cannot delete XML File, 验证失败时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18333233/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com