如何从ouside读取jar资源中的文件 [英] How to read a file inside a jar's resources from ouside the jar
问题描述
我在abc.jar的类路径中有一个文件X.json。 abc.jar中有一个readFile方法,该文件的读取方式为
I have a file X.json inside abc.jar in its classpath. There is a method readFile in abc.jar which reads the file as
URL url = Abc.class.getClassLoader().getResource("X.json");
File file = new File(url.toURI());*
如果我从jar的上下文中运行它很好,即abc.jar内部某个文件中的main方法
which reads it fine if i run it from within the jar's context i.e main method in some file inside the abc.jar
但是当从abc.jar外部从某些调用readFile时其他代码因 java.lang.IllegalArgumentException而失败:URI不是分层的
But when readFile is called from from outside of abc.jar from some other code it fails with java.lang.IllegalArgumentException: URI is not hierarchical
如何获取File对象通过从罐子的上下文外部调用方法readFile?
How do I get the File object by calling the method readFile from outside the jar's context ?
推荐答案
在部署时,这些资源将成为 embedded-resource 。在这种情况下,必须通过 URL
而不是 File
访问资源。有关标签的信息,请参见信息页面,以了解形成 URL $的方法c $ c>。
By the time of deployment, those resources will become an embedded-resource. That being the case, the resource must be accessed by URL
instead of File
. See the info page for the tag, for a way to form an URL
.
这篇关于如何从ouside读取jar资源中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!