gpt4 book ai didi

Java Validator 在失败时锁定文件——我做错了什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:22:51 26 4
gpt4 key购买 nike

我正在尝试根据 Java 中的模式验证 XML 文件,问题是如果文件验证失败,则文件将被锁定,直到应用程序终止。如果输入文件有效,则文件不会被锁定,一切都很好。

我正在使用 javax.xml.validation.Validatorvalidate() 方法。这看起来很简单,并且在验证通过时就可以了。我只能假设我在错误处理中遗漏了一些东西,但是 Validator 的 API 似乎没有提供任何有用的东西。谁能阐明我在这里做错了什么?

我已将所有这些简化为下面的一个独立类。如果您运行它,那么在扫描程序启动时,检查输入文件,您可以看到它现在已被锁定。如果您需要,我可以提供输入和结构文件。

谢谢,

菲尔


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.net.URI;
import java.util.Scanner;

import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

public class ValidationTest {

public static void validate(URI xmlLocation, URI schemaLocation) throws Exception {

SchemaFactory schemaFactory = SchemaFactory.newInstance( "http://www.w3.org/2001/XMLSchema" );

Source schemaSource = new StreamSource(schemaLocation.toString());
Schema schema = schemaFactory.newSchema(schemaSource);

Validator schemaValidator = schema.newValidator();

StreamSource source = new StreamSource(xmlLocation.getPath());
schemaValidator.validate( source );
}


public static void main(String[] args) throws Exception {
File srcFile = new File("c:/aaa/MySrc-Broken.xml");
File schema = new File("c:/aaa/MyStructureDefinition.xsd");

try {
ValidationTest.validate(srcFile.toURI(), schema.toURI());
} catch(Exception e) {
System.err.println(e);
}

// Use a Scanner to pause the thread, so that I can
// go and check the file's permissions.
Scanner scan = new Scanner(System.in);
scan.nextLine();
}
}

更新:

我有一点技巧,它提供了一个(糟糕的)解决方案。我将自定义 errorHandler 添加到 schemaValidator。这个 errorHandler 只是将任何错误存储在一个成员变量中。这意味着 validator 将始终成功,从而释放对输入文件的所有锁定。但是,我必须检查错误处理程序以查看是否有任何错误,如果有则抛出错误。这不是很好,但确实让我解决了这个问题。

最佳答案

请注意,不允许使用 StreamSource 实例。( http://docs.oracle.com/javase/1.5.0/docs/api/javax/xml/validation/Validator.html )

URL xmlFileURL = xmlFileToCheck.toURI().toURL();
InputStream inputStream = xmlFileURL.openStream();
InputSource is = new InputSource(inputStream);
SAXSource saxSource = new SAXSource(is);

xmlValidator.validate(saxSource);

inputStream.close(); // this is probably important...

关于Java Validator 在失败时锁定文件——我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8170294/

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