14

I having file in the location

--src
  --> main
   --> config
    --> application
     --> context
      --> reference
       --> user
        --> user.xml

where

    --src
      --> main
       --> config

is in the classpath. Now I am trying to access the file using

Resource resource = new ClassPathResource("classpath**:/application/context/references/user/user.xml");
File file = resource.getFile();

But I getting FileNotFoundException, I tried with

Resource resource = new ClassPathResource("classpath:/application/context/references/user/user.xml");
File file = resource.getFile();

too, but still I getting the exception. Can someone help me to understand the working of ClassPathResource and right solution?

Stefan van den Akker
  • 6,661
  • 7
  • 48
  • 63
  • 2
    Try to determine the starting path in ClassPath, `Resource resource = new ClassPathResource("" or File.seperator); resource.getFile().getAbsolutePath();` So that you can give the appropriate value inside new CPR() based on above result – The Coder Apr 13 '16 at 05:02
  • 1
    remove "classpath:", see [this answer](http://stackoverflow.com/a/8725288/180100) and http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/io/ClassPathResource.html#ClassPathResource-java.lang.String- –  Apr 13 '16 at 05:23
  • @RC., you are right, Yesterday I tried the same, but I think I didn't test it correctly. – Suganthan Madhavan Pillai Apr 13 '16 at 05:53

1 Answers1

25

Use as below

Resource resource = new ClassPathResource("/application/context/references/user/user.xml");
File file = resource.getFile();
KayV
  • 12,987
  • 11
  • 98
  • 148
  • 5
    The leading slash is unnecessary according to the [class documentation](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/io/ClassPathResource.html): _A leading slash will be removed, as the ClassLoader resource access methods will not accept it._ – David Riccitelli Jul 09 '19 at 08:18
  • `java.io.FileNotFoundException: class path resource [logging_date.txt] cannot be resolved to URL because it does not exist` It cannot find the file. – likejudo Mar 24 '23 at 22:01