[英]how do I access a resource file from a dependent jar?
I have an android application that has a dependent library I created, referenced in build.gradle via compile {artifact_name}. 我有一个Android应用程序,该应用程序具有我创建的一个依赖库,通过编译{artifact_name}在build.gradle中对其进行了引用。 The library needs to access a resource file in its resources dir(src/main/resources).
库需要在其资源目录(src / main / resources)中访问资源文件。 Here is what I want to accomplish, but can't:
这是我要完成的工作,但不能完成:
URL url = helper.class.getClassLoader().getResource("myfile.json");
FileReader fr = new FileReader(url.getPath());
myfile.json is in src/main/java/resources of my library. myfile.json在我库的src / main / java / resources中。 this led to an app crash saying "jar:file:/data/app/com.my.app/base.apk!/myfile.json" not found when trying to create the FileReader.
尝试创建FileReader时,导致找不到应用程序崩溃,提示“ jar:file:/data/app/com.my.app/base.apk!/myfile.json”。
However, it can be found if I run it in a client class in the library itself. 但是,如果我在库本身的客户端类中运行它,则可以找到它。
Updated (I have some more time to give full answer) 更新(我还有更多时间给出完整答案)
In your case ClassLoader
of helper class have an access to your file (there are why you get "jar:file:/data/app/com.my.app/base.apk!/myfile.json"
in your FileReader
instance). 在您的情况下,辅助类的
ClassLoader
可以访问您的文件(这就是为什么在FileReader
实例中获得"jar:file:/data/app/com.my.app/base.apk!/myfile.json"
)。
But FileReader
don't understand full-qualified URL
s (only URL
s with scheme file:
or without any scheme, but you have outer scheme jar:
- file accessible from jar file). 但是
FileReader
不能理解标准URL
(仅包含具有方案file:
URL
或没有任何方案,但是您具有外部方案jar:
-可从jar文件访问的文件)。
To read data in this case you should1 use combination of InputStreamReader
and Class.getResourceAsStream
: 在这种情况下,要读取数据,应使用
InputStreamReader
和Class.getResourceAsStream
组合:
ClassLoader cl = helper.class.getClassLoader();
InputStream is = cl.getResourceAsStream("myfile.json");
Reader r = new InputStreamReader(is);
PS in common situations you don't need access ClassLoader
directly - Class
will access it by itself.PS
在通常情况下,您不需要直接访问 ClassLoader
Class
将自行访问它。Only rare cases should use access to ClassLoader
and in this situations you should really understand Class
es and ClassLoader
s very clear.只有极少数情况下应该使用对 I found out some usefull information: ClassLoader
访问权限,在这种情况下,您应该真正理解Class
es和ClassLoader
。Class
es method (both getResource
and getResourceAsStream
) checks file only in same package while ClassLoader
s methods checks (additionally) at root path (as I remember some of them checks in both places and today I checked that Class don't check root of jar file). 我发现了一些有用的信息:
Class
es方法( getResource
和getResourceAsStream
)仅在同一包中检查文件,而ClassLoader
的方法(另外)在根路径中检查文件(因为我记得其中一些在两个地方都进行了检查,今天我检查了该类不要检查jar文件的根目录)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.