java - getResource will always return null -
this driving me crazy. have simple eclipse project src folder , class in it. can't seem getresource find it. doing wrong?
import java.net.url; public class contexttest { public static void main(string[] args) { url url = contexttest.class.getresource("/src/contexttest.java"); system.out.println(url); } }
if right-click on class name, path /testsproject/src/contexttest.java
, default classpath according classpath tab in run configurations testproject
.
it doesn't work /bin/contexttest.java
, /contexttest.java
, contexttest.java
either.
when load resources using contexttest.class.getresource("/....")
leading /
translated absolute path. here absolute means root package (i.e. default package).
in eclipse root package considered 1 under src
folder. compiled classes placed under bin
folder , if create jar see root package not src
or bin
folders whatever folders inside it. (for example com
).
so correct way load resource using class absolute path contexttest.class.getresource("/contexttest.java");
. if file contexttest.java
in root package of wherever compiled classes are, found , returned.
i hope clears picture.
update: comments below not clear trying do. when use getresource()
you not loading file a resource classpath. correctly find resource if files inside jar file. above example work file trying load resource should in classpath (i.e. under bin
folder since root of classpath when execute inside eclipse). if trying load file outside of classpath don't try load resource, use file
instead.
Comments
Post a Comment