-2

I'm trying to access a file test.gif located at (src/main/resources/test.gif in Eclipse),from my program using the absolute path using the ClassLoader, in the following manner

String absPath=this.getClass().getResource("/test.gif").toString();
System.out.print(Path);// prints the absolute path /Users/Abby/Project/SubFolder/ProjectName/target/classes/test.gif - the file exists at the location.



 String relPath= "src/main/resources/test.gif";

However, accessing absPath causes a FileNotFoundException in my program whereas using relPath does not.

What exactly am I doing wrong? And how do I correctly access the file using the absolute path (via ClassLoader)

userNotFound
  • 347
  • 1
  • 4
  • 13
  • If this `Users/[username]/Project/SubFolder` is the correct absolute path, then this is missing a leading slash. – Tom Nov 20 '14 at 07:08
  • `Users/Abby/Project/SubFolder/ProjectName/target/classes/test.gif` is not an absolute path - you're missing, in the very least, a `/` in the beginning of it. – Mureinik Nov 20 '14 at 07:08
  • possible duplicate of [Where to put a textfile I want to use in eclipse?](http://stackoverflow.com/questions/2850674/where-to-put-a-textfile-i-want-to-use-in-eclipse) – KNU Nov 20 '14 at 07:14
  • @Mureinik:Corrected it. – userNotFound Nov 20 '14 at 07:17

2 Answers2

0

You speak about relative path, yet the path you are testing with "/test.gif" starts with a /, why ! Please have a look at other response before adding a new question. Preferred way of loading resources in Java

Community
  • 1
  • 1
Mooolo
  • 428
  • 2
  • 7
0

Use the URL and File classes:

    URL url = getClass().getResource("/test.gif");
    File file = new File(url.toURI();
    System.out.println(file).getCanonicalPath());

Also, getCanonicalPath() will return the absolute path for a file. And you may want to check for null in case the resource is not found.

blagerweij
  • 3,154
  • 1
  • 15
  • 20