[英]Failing to load resource when running java program from command line
我可以从我的IDE(IntelliJ)内正确运行Java程序; 但是,当我尝试从命令行运行同一程序时,它将失败。 引发的错误是:
RuntimeUnmarshallException: org.xml.sax.SAXParseException; schema_reference.4: Failed to read schema document 'file:/home/Experiments/file:/home/path/to/jar/my.jar!/configuration.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.
堆栈跟踪指出问题出在这里:
String SCHEMA_FILE_PATH = "configuration.xsd";
ClassLoader classLoader = getClass().getClassLoader();
URL resource = classLoader.getResource(SCHEMA_FILE_PATH); // <- breaks here
return new File(resource.getFile());
我将找不到的架构文件存储在IDE中标记为资源根的目录中。 我敢打赌,当我从命令行运行时,由于我是从其他工作目录运行,因此它不知道在哪里查找。 我尝试在命令行上设置类路径,以便能够在包含模式的目录中查找,但这无济于事。 我想我可以将工作目录设置为从IDE运行时的工作目录,但这似乎是一个可怕的设计选择。
谢谢你的帮助。
编辑:我刚刚确认jar中包含configuration.xsd文件,但是无论出于什么原因,它似乎都在奇怪的地方寻找它...
运行.jar
,其内容不会解压缩,而是直接从.jar
读取。 因此,您正在加载的资源不能表示为File
(它仍然嵌套在.jar
)。 您可以在错误消息中看到-感叹号后的部分是jar
资源的路径。
我建议改用Classloader.getResourceAsStream(..)
。 它透明地处理加载。
请注意,您可以使用new StreamSource(InputStream)
从流构造对架构文档的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.