• Post Reply Bookmark Topic Watch Topic
  • New Topic

getResource  RSS feed

 
Meet Gaurav
Ranch Hand
Posts: 492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Am just using SomeClass.class.getResource("com/some_package/images/pic.gif"); for loading a file. But this code is searching only in the java classpath. But I need to the file from any path say from D:/ or c:/ .. Please assist me
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you read the API for java.lang.Class.getResource(), it tells you that it only goes to the classpath. If you want other behaviour you will need to find and load the java.io.File yourself
 
Meet Gaurav
Ranch Hand
Posts: 492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks David. Any other way to load a file

My requirement is

currelntly : java.net.URL hedlpURL = HelperClass.class.getResource("test.pdf");

instead I need to load a file from local path may be c: or d:

Expected : java.net.URL hedlpURL = HelperClass.class.getResource("c:\\test.pdf");

 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you know the absolute location you can use a java.io.File, as I mentioned.
You cannot use Class.getResource if it is not on the classpath. That is not what it is designed to do.
 
Rob Spoor
Sheriff
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With a URLClassLoader you can use getResource and getResourceAsStream, but you must provide the absolute path of the resource. For example:

However, as said, if you know the location of the file, using a FileInputStream or the way I created URLs in the above code is much easier. The URLClassLoader would be more appropriate if the paths are configurable.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!