ClassPathResource 未获取类路径
在我的应用程序中,我想使用文件夹 media/src/main/resources/testMediaExif
中存在的资源
为了获取该路径,我使用了位于 media 中的这段代码/src/main/java/com/project/MyClass.java
:
ClassPathResource resource = new ClassPathResource("classpath:testMediaExif");
File file = resource.getFile();
String absolutePath = file.getAbsolutePath();
显示的错误是:
java.io.FileNotFoundException: class path resource [classpath:testMediaExif] cannot be resolved to URL because it does not exist
如果我更改该代码:
ClassPathResource resource = new ClassPathResource("testMediaExif");
变量absolutePath采用这个值:
/Users/blanca/desarrollo/media/target/test-classes/testMediaExif
为什么它指向目标路径?我怎样才能改变它?
In my application, I would like to use a resource that exist in a folder media/src/main/resources/testMediaExif
To get that path, I used this piece of code, located in media/src/main/java/com/project/MyClass.java
:
ClassPathResource resource = new ClassPathResource("classpath:testMediaExif");
File file = resource.getFile();
String absolutePath = file.getAbsolutePath();
The error shown is:
java.io.FileNotFoundException: class path resource [classpath:testMediaExif] cannot be resolved to URL because it does not exist
If I change that code:
ClassPathResource resource = new ClassPathResource("testMediaExif");
The variable absolutePath takes this value:
/Users/blanca/desarrollo/media/target/test-classes/testMediaExif
Why does it point to the target path? How could I change it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
new ClassPathResource("classpath:testMediaExif")
有两个问题:classpath:
前缀仅在配置文件(例如 XML 文件)中使用,不应使用如果您直接使用ClasspathResource
。classpath:testMediaExif
引用类路径根目录中的资源,而不是相对于您在其中进行引用的文件。试试这个:
或者
这些将构造一个相对于
MyClass
的对名为testMediaExif
的资源的引用。还有一件事:
ClasspathResource.getFile()
只能在资源确实是文件的情况下工作。如果它打包在 JAR 中,那么它就不起作用。There are two problems with
new ClassPathResource("classpath:testMediaExif")
:classpath:
prefix is only used in config files (e.g. XML files), and should not be used if you're usingClasspathResource
directly.classpath:testMediaExif
refers to a resource in the root of the classpath, not relative to the file in which you're making the reference.Try this instead:
or
These will construct a refernce to a resource called
testMediaExif
relative toMyClass
.One more thing:
ClasspathResource.getFile()
will only work in the resource really is a file. If it's packed in a JAR, then it won't work.我的猜测是绝对路径问题是由于 maven POM 目标中的 outputDirectory 造成的。在我的项目中,outputDirectory war/WEB-INF/classes 是从这里执行类的。如果我将其更改为某个垃圾值,该类将不再被执行。
所以我相信绝对路径必须与 .class 文件的位置有关。希望这有帮助。
My guess is that the absolute path issue is because of the outputDirectory in the target of your maven POM . In my project the outputDirectory war/WEB-INF/classes and the it is from here the classes get executed . If I change it to some junk value , the class no longer gets executed .
So I believe the absolute path has to do something with the location of your .class files . Hope this helps .