问题
I have the following project-tree:
I can access the 290.gif file in the path: Java GUI/src/dk/resources/290.gif by using the following command:
this.getClass().getResource("/dk/resources/290.gif")
But I can't access the 290.gif file in the path: Java GUI/resources2/290.gif by using the following command:
this.getClass().getResource("/resources2/290.gif")
I am trying to access the 290.gif file from the HelloWorldFrame.java class. I want to access the 290.gif file in the path: Java GUI/resources2/290.gif!
What am I doing wrong?
回答1:
You have declared both src
and resources2
directories as source folders in Eclipse.
When Eclipse builds your app, it copies recources to the build
folder, and so:
- the files from
dk.resources
package are accessible via/dk/resources/290.gif
- the files from
resources2
folder are not in any package, and are accessible via/290.gif
If you want the file to be accessible via /resources2/290.gif
, then create a package named resource2
under the src
folder.
回答2:
Seems that the folders src
and resources2
are both in the build path. Have you tried this.getClass().getResource("/290.gif")
?
回答3:
During runtime of the artifact you can access resources with
InputStream resource = SomeClass.class.getResourceAsStream("<file or directory name"))
or
URL resource = SomeClass.class.getResource("<file or directory name"))
where SomeClass is a class in the artifact. The first way will give you an InputStream that you can use to read the contents of the file, the second way will return a URL that you can use to find out the path of the file or directory or move along the directory tree.
来源:https://stackoverflow.com/questions/11121083/cannot-access-resource-by-using-the-getresources-method