Java in Eclipse: Where do I put files on the filesystem that I want to load using getResource? (e.g. images for an ImageIcon)
Asked Answered
E

2

52

I know the file needs to be where the getClass().getResource(filename) can find it, but I don't know where that is.

I'm interested both in where to put the files on the filesystem itself, and how to go about using Eclipse's functionality to set up the resources.

Elamite answered 6/11, 2008 at 20:43 Comment(0)
M
62

For Eclipse, typically all you need to do is set up a folder somewhere within your source code directory. For instance, if the directory containing your source is /src then you can create a /src/resources folder to place your images/files in. Then, within your class you do a getResource("/resources/image.png") to retrieve it.

You can also place the image/file within the same folder/package as the class trying to access it if you wish (example: place the image.png in the com.mycompany package with the com.mycompany.Foo class that needs to access it and call getResource("image.png")), but I've found it's easier to keep resources like images and other files in their own special directory outside of the class folders -- they're just easier to manage that way.

In Eclipse, whenever you do a build, the files within this resource directory will be copied over into your build directory along with your compiled classes.

It's important to note that if you have "Build Automatically" turned on in Eclipse (as most people do) any resources in this directory that get changed outside of Eclipse (i.e. you edit an image using an image editing tool) that the IDE may not always detect this change. Usually doing a refresh on the project folder will ensure that the file gets updated in the build in these situations.

Marquisette answered 6/11, 2008 at 21:40 Comment(1)
I would add that in case Eclipse doesn't correctly handle the resource directory you put in src/, you need to "include" it but not use it as a "source folder". You can do this by bringing up the context menu for the folder (right click) and go to Build Path -> Remove from Build Path, IncludeManhandle
M
8

You can either put them in the src folder alongside your classes, or you can create a new source folder for the purpose (usually called resources), although you'll locate them identically from code.

Then you get at them using getResource("/com/x/y/foo.png").

Marginate answered 6/11, 2008 at 20:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.