从 Java 访问 gradle 资源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24940815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing gradle resources from Java
提问by magomar
I have a gradle-based java project with this structure
我有一个具有这种结构的基于 gradle 的 java 项目
.
├── myproject
│ ├── src
│ | └── main
│ | ├── java
│ | └── resources
│ | └── myresource.xml
| ├── build
| | ├── classes
| | | └── main
│ | | └── myresource.xml
| | ├── resources
I'm trying to access some files in the resourcesfolder using a ClassLoader, like this
我正在尝试使用类加载器访问资源文件夹中的某些文件,如下所示
ClassLoader.getSystemClassLoader().getResoure("/myresource.xml");
but it does not find the file.
但它没有找到该文件。
The only way I have found to access those files is by exploring the known structure of the project
我发现访问这些文件的唯一方法是探索项目的已知结构
Path resourcesPath= FileSystems.getDefault().getPath(System.getProperty("user.dir"), "/src/main/resources/");
Any idea on what am I doing wrong?
知道我做错了什么吗?
采纳答案by magomar
Well, it seems my difficulties came from another problem (resources not being copied to the proper places). Once I solved that problem, the ClassLoader was able to find my resources using either of these two forms:
好吧,看来我的困难来自另一个问题(资源没有被复制到适当的地方)。一旦我解决了这个问题,ClassLoader 就能够使用以下两种形式之一找到我的资源:
ClassLoader.getSystemClassLoader().getResource("./myresource.xml");
ClassLoader.getSystemClassLoader().getResource("myresource.xml");
Edit:When using the jar embedded in other applications, the former solution do not work, use this in that case:
编辑:当使用嵌入在其他应用程序中的 jar 时,以前的解决方案不起作用,在这种情况下使用它:
Thread.currentThread().getContextClassLoader().getResource("myresource.xml")
回答by Radim
http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResource(java.lang.String)
http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResource(java.lang.String)
For example something like MyMain.class.getResource("/config.txt")
or use relative path when appropriate.
例如,MyMain.class.getResource("/config.txt")
在适当的时候类似或使用相对路径。
回答by u10914959
Maybe you should use it this way:
也许你应该这样使用它:
Thread.currentThread().getContextClassLoader().getResource("myresource.xml")
If i use ClassLoader.getSystemClassLoader().getResource("myresource.xml")
如果我使用 ClassLoader.getSystemClassLoader().getResource("myresource.xml")
When I use it as a jar package embedded in other applications, I still have no access to resources.
当我将其作为嵌入其他应用程序的jar包使用时,我仍然无法访问资源。