简体   繁体   中英

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. main.jar has schema.jar on its classpath as a maven dependency. I'm able to find the sample.xsd file when I use the this.getClass().getClassLoader().getResourceAsStream, but I need a java.io.File. What is the most memory efficient approach to supply the java.io.File parameter?

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.

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). JAXB will under the covers grab the InputStream from the supplied URL by URL#openStream() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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