java 通过相对路径从资源加载文件(Spring)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32590532/
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
Load file from resources by relative path (Spring)
提问by anntheitroadq
I have spring project. My file here: /src/main/java/resources/file.txt.
我有春季项目。我的文件在这里:/src/main/java/resources/file.txt。
How I can get full path of this?
我怎样才能得到这个的完整路径?
If I run from test it works:
如果我从测试运行它可以工作:
String path = System.getProperty("user.dir") + "/src/main/java/resources/file.txt";
But if I use tomcat, it shows another path inside tomcat folder. So spring cannot find this path.
但是如果我使用 tomcat,它会在 tomcat 文件夹中显示另一个路径。所以春天找不到这条路。
EDIT:this.getClass().getClassLoader().getResource("file.txt") is null
编辑:this.getClass().getClassLoader().getResource("file.txt") 为空
UPDATED: sorry for stupid question. It works, I set wrong name of file.
更新:抱歉愚蠢的问题。它有效,我设置了错误的文件名。
回答by Subhrajyoti Majumder
As file - file.txt
is in resources directory, normally this would be copied to class-path
by build process(tool like Maven, Gradle). And this would easy with to load file with relative path.
作为文件 -file.txt
在资源目录中,通常这会被class-path
构建过程复制到(像 Maven、Gradle 这样的工具)。这很容易加载具有相对路径的文件。
This thread had extensively talked about how to load file from class-path
.
How to really read text file from classpath in Java
该线程广泛讨论了如何从class-path
.
如何真正从 Java 中的类路径读取文本文件
回答by luboskrnac
With Spring you can use class ClassPathResource
. It can read files from java classpath without too much pure Java boilerplate code.
使用 Spring,您可以使用 class ClassPathResource
。它可以从 java classpath 读取文件,而无需太多纯 Java 样板代码。