16

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?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Blanca Hdez
  • 3,513
  • 19
  • 71
  • 93

2 Answers2

19

There are two problems with new ClassPathResource("classpath:testMediaExif"):

  1. The classpath: prefix is only used in config files (e.g. XML files), and should not be used if you're using ClasspathResource directly.
  2. 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:

new ClasspathResource("testMediaExif", getClass())

or

new ClasspathResource("testMediaExif", MyClass.class)

These will construct a refernce to a resource called testMediaExif relative to MyClass.

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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • Thanks, with your approach, the problem comes when I try to get the absolute path. new ClasspathResource("testMediaExif", getClass()) gets the path where the class is, but getAbsolutePath points to target folder again – Blanca Hdez Jan 04 '12 at 11:12
6

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 .

Aravind A
  • 9,507
  • 4
  • 36
  • 45