Eclipse 中的 Java:我应该将要使用 getResource 加载的文件系统上的文件放在哪里?(例如 ImageIcon 的图像) [英] Java in Eclipse: Where do I put files on the filesystem that I want to load using getResource? (e.g. images for an ImageIcon)

查看:23
本文介绍了Eclipse 中的 Java:我应该将要使用 getResource 加载的文件系统上的文件放在哪里?(例如 ImageIcon 的图像)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道文件需要在 getClass().getResource(filename) 可以找到的地方,但我不知道那在哪儿.

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

我对将文件放在文件系统本身的何处以及如何使用 Eclipse 的功能设置资源感兴趣.

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.

推荐答案

对于 Eclipse,通常您需要做的就是在源代码目录中的某处设置一个文件夹.例如,如果包含你的源代码的目录是 /src 那么你可以创建一个 /src/resources 文件夹来放置你的图像/文件.然后,在你的类中做一个 getResource("/resources/image.png") 来检索它.

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.

如果您愿意,您也可以将图像/文件放在与尝试访问它的类相同的文件夹/包中(例如:将 image.png 放在 com.mycompany 包中com.mycompany.Foo 需要访问它并调用 getResource("image.png")) 的类,但我发现保留图像和其他文件位于类文件夹之外的它们自己的特殊目录中——这样管理起来更容易.

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.

在 Eclipse 中,无论何时进行构建,此资源目录中的文件都将与已编译的类一起复制到构建目录中.

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.

请务必注意,如果您在 Eclipse 中打开了自动构建"(大多数人都这样做),则此目录中的任何资源在 Eclipse 之外发生更改(即您使用图像编辑工具编辑图像)IDE 可能无法始终检测到此更改.通常对项目文件夹进行刷新将确保在这些情况下文件在构建中得到更新.

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.

这篇关于Eclipse 中的 Java:我应该将要使用 getResource 加载的文件系统上的文件放在哪里?(例如 ImageIcon 的图像)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆