简体   繁体   English

从命令行运行Java程序时无法加载资源

[英]Failing to load resource when running java program from command line

I am able to run a java program from within my IDE (IntelliJ) properly; 我可以从我的IDE(IntelliJ)内正确运行Java程序; however, when I attempt to run the same program from the command line it fails. 但是,当我尝试从命令行运行同一程序时,它将失败。 The error being thrown is: 引发的错误是:

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>.

The stack trace points out that the issue is here: 堆栈跟踪指出问题出在这里:

String SCHEMA_FILE_PATH = "configuration.xsd";
ClassLoader classLoader = getClass().getClassLoader();
URL resource = classLoader.getResource(SCHEMA_FILE_PATH); // <- breaks here
return new File(resource.getFile());

I have the schema file that cannot be found stored in a directory that is marked as a resource root in my IDE. 我将找不到的架构文件存储在IDE中标记为资源根的目录中。 I am betting that when I run from the command line that since I am running from a different working directory that it does not know where to look. 我敢打赌,当我从命令行运行时,由于我是从其他工作目录运行,因此它不知道在哪里查找。 I have tried setting the classpath on the command line to be able to look in the directory that contains the schema, but this did not help. 我尝试在命令行上设置类路径,以便能够在包含模式的目录中查找,但这无济于事。 I imagine that I could set the working directory to what it is when I run from my IDE, but this seems like a horrible design choice. 我想我可以将工作目录设置为从IDE运行时的工作目录,但这似乎是一个可怕的设计选择。

Thanks for any help. 谢谢你的帮助。

EDIT: I just confirmed that the configuration.xsd file is contained in the jar, but for whatever reason it seems to be looking for it in weird places... 编辑:我刚刚确认jar中包含configuration.xsd文件,但是无论出于什么原因,它似乎都在奇怪的地方寻找它...

When running a .jar , its content is not unpacked, but read directly from the .jar . 运行.jar ,其内容不会解压缩,而是直接从.jar读取。 Therefore the resource you are loading can not be represented as a File (it is still nested inside the .jar ). 因此,您正在加载的资源不能表示为File (它仍然嵌套在.jar )。 You can see that in the error message - the part after the exclamation mark is the path to the resource inside the jar . 您可以在错误消息中看到-感叹号后的部分是jar资源的路径。

I would recommend using Classloader.getResourceAsStream(..) instead. 我建议改用Classloader.getResourceAsStream(..) It handles the loading transparently. 它透明地处理加载。

Note that you can use new StreamSource(InputStream) to construct a reference to the schema document from the stream. 请注意,您可以使用new StreamSource(InputStream)从流构造对架构文档的引用。

Here is some official information about resource loading, and this question may be of interest. 是有关资源加载的一些官方信息, 这个问题可能引起您的兴趣。

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

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