用 Java 组织资源 [英] Organize resources in Java

查看:24
本文介绍了用 Java 组织资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Java 中组织资源?

How can I organize resources in Java?

例如,当我将使用图片嵌入到我的应用程序中时,我可以将它存储在哪个文件夹中?因为当我在一个可执行的 .jar 文件中制作我的程序时,所有资源(如图片、文本文件)都在我存储它的文件夹之外.

For example, when I will use pictures to be embedded in my application, in what folder can I store it? Because when I make my program in an executable .jar file all the resources like pictures, text file, it goes outside the folder where I stored it.

推荐答案

一个常见的做法是为资源预留一个包.您可以将它放在任何地方,这取决于需要访问这些资源的类(没有规则,这只是组织逻辑的问题).例如,您的类 project.gui.Main 需要加载一些图像,然后您可以创建一个 project.gui.data 包并将您的资源存储在其中.要从 Main 加载这些资源,请使用以下代码:

A common practice is to reserve a package to resources. You can place it anywhere, depending on the classes needing to access those resources (there's no rule, it's just a matter of organization logic). For example, your class project.gui.Main needs to load some images, you can then create a project.gui.data package and store your resources in it. To load these resources from Main, use the following piece of code :

Main.class.getResource("data/img.png");

这样就可以通过本地路径访问资源了.如果应用程序 si 希望打包在 jar 中,切勿使用绝对路径.

This way, you can access the resource with a local path. Never use absolute paths if the application si expected to be packed in a jar.

这篇关于用 Java 组织资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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