简体   繁体   English

在运行时在类路径上加载java.io.File

[英]Load java.io.File At Runtime On Classpath

I have two jars (main.jar and schema.jar) and I need to read a schema file (located in src/main/resources/sample.xsd) from schema.jar in a class within main.jar. 我有两个jar(main.jar和schema.jar),我需要从main.jar中的类中的schema.jar读取模式文件(位于src / main / resources / sample.xsd中)。 main.jar has schema.jar on its classpath as a maven dependency. main.jar在其类路径上具有schema.jar作为Maven依赖项。 I'm able to find the sample.xsd file when I use the this.getClass().getClassLoader().getResourceAsStream, but I need a java.io.File. 使用this.getClass()。getClassLoader()。getResourceAsStream时,我可以找到sample.xsd文件,但我需要一个java.io.File。 What is the most memory efficient approach to supply the java.io.File parameter? 提供java.io.File参数最节省内存的方法是什么?

main.jar: main.jar:

InputStream in = this.getClass().getClassLoader()
        .getResourceAsStream("/resources/sample.xsd");

Sample sample = new Sample();
//set sample data here
 Marshaller marshaller = JAXBContext.newInstance(Sample.getClass()).createMarshaller();
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema s = schemaFactory.newSchema(new File("/resources/sample.xsd"));
marshaller.setSchema(s);
    marshaller.marshal(Sample, XML);

Just use SchemaFactory#newSchema(URL) method instead. 只需使用SchemaFactory#newSchema(URL)方法即可。

URL url = getClass().getClassLoader().getResource("/resources/sample.xsd");
// ...
final Schema s = schemaFactory.newSchema(url);

No need to massage the InputStream into a File which isn't nicely possible anyway (you could create a temp file, but that's plain clumsy). 无需将InputStream压缩到一个File ,这是不可能的(您可以创建一个临时文件,但这很笨拙)。 JAXB will under the covers grab the InputStream from the supplied URL by URL#openStream() . JAXB会在URL#openStream()通过URL#openStream()从提供的URL获取InputStream

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

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