简体   繁体   English

从Maven资源获取文件的路径名

[英]Get pathname to file from Maven resources

I currently have a method that validates an XML file by comparing it to an XSD file. 我目前有一种通过将XML文件与XSD文件进行比较来验证XML文件的方法。

private boolean validateXmlFile() {
    try {
        SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        Schema schema;

        schema = factory.newSchema(new File("school.xsd"));

        Validator validator = schema.newValidator();
        Source source = new StreamSource(new File("school.xml"));

        validator.validate(source);

        return true;
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}

Initially, the XSD file was located in the main directory, but now I am currently trying to convert my project so that it is 'mavenised', which involves putting all of my files in a 'resources/' directory. 最初,XSD文件位于主目录中,但是现在我目前正在尝试转换项目,以便对其进行“修饰”,这涉及将我的所有文件都放置在“ resources /”目录中。

How do I call the pathname to the XSD file now that it is in the resources directory? 既然XSD文件位于资源目​​录中,该如何命名? Obviously I can't do it this way: 显然我不能这样:

schema = factory.newSchema(new File("resources/school.xsd"));

Does it involve referring to the file as an InputStream? 是否涉及将文件称为InputStream?

Many thanks 非常感谢

这就是我一直在寻找的东西,谢谢:

schema = factory.newSchema(new File(this.getClass().getResource("school.xsd").toURI()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM