簡體   English   中英

在運行時在類路徑上加載java.io.File

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

我有兩個jar(main.jar和schema.jar),我需要從main.jar中的類中的schema.jar讀取模式文件(位於src / main / resources / sample.xsd中)。 main.jar在其類路徑上具有schema.jar作為Maven依賴項。 使用this.getClass()。getClassLoader()。getResourceAsStream時,我可以找到sample.xsd文件,但我需要一個java.io.File。 提供java.io.File參數最節省內存的方法是什么?

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

只需使用SchemaFactory#newSchema(URL)方法即可。

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

無需將InputStream壓縮到一個File ,這是不可能的(您可以創建一個臨時文件,但這很笨拙)。 JAXB會在URL#openStream()通過URL#openStream()從提供的URL獲取InputStream

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM