在Eclipse中将Java项目的资源(图像,数据文件等)存储在哪里? [英] Where to store resources for a java project in Eclipse (images, data files, ...)?

查看:700
本文介绍了在Eclipse中将Java项目的资源(图像,数据文件等)存储在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定这个基本问题是否已经在SO上得到了解决。

Not sure this basic question has already been answered on SO.

从参考资料以及在SO上找到的答案,我知道在Eclipse中是源文件夹是一个文件夹,JDT将在该文件夹中搜索源文件并对其进行编译。

From the reference and also answers found on SO, I understand that in Eclipse a "source folder" is a folder that JDT will search for source files, and compile them.

还提到每个源文件夹都可以有一个副本来存储编译的类。也许这就是为什么将项目通常的 src文件夹的内容编译为 bin文件夹的原因(在Eclipse中使用此类src / bin项目选项时)。

It has been mentioned also that each source folder may have a counterpart to store compiled classes. Maybe this is why the content of the usual "src" folder of a project is compiled into a "bin" folder (when using such src/bin project option in Eclipse).

问题:在哪里存储其他非源文件,例如图标,安全策略还是数据文件?我猜这在常规文件夹中,但是在项目层次结构中的哪个级别(通常)?是否可以将其放在源文件夹中(我们为什么要这样做)?编译或导出到.jar文件后,在哪种情况下将文件复制到.jar中会发生什么?

Question: Where to store additional non-source files, e.g. an icon, a security policy, or a data file? I guess this is in a "regular" folder, but at which level in the project hierarchy (usually)? Is it possible to put it in a source folder or not (why would we do that)? What happens after compilation, or export to a .jar file, under which conditions are the files copied in the .jar? Is the relative path preserved?

推荐答案

这是纯常规方法吗?您可以将它们全部存储在 src 中。

This is purely conventional. You can store them all in src if you want.

但是,如果您要坚持使用Maven或Gradle约定,那么您应该有这样的东西:

However, if you want to stick to Maven or Gradle conventions, then you should have something like that:


  • src / main / java :主源文件,将被编译然后分发(jar等)

  • src / main / resources :主资源,

  • src / test / java :测试源文件,又名Junit测试

  • src / test / resources :测试资源。

  • src/main/java : main source file, that will be compiled and then distributed (jar, etc)
  • src/main/resources : main resources, distributed.
  • src/test/java : test source file, aka Junit test
  • src/test/resources : test resources.

Maven将编译所有Java放入 target / classes 并将所有资源复制到 target / classes 。对于测试,将是 target / test-classes

Maven would compile all Java into target/classes and copy all resources into target/classes. For test, it would be target/test-classes.

此外,如果您要访问资源,在您的类所在的Jar中,您不应使用 new File( ...) Paths.get(...) ,但 getResourcesAsStream 或其对应的 getResource

Beside, if you want to access a resource, that in the Jar where your classes are, you should not use new File("...") or Paths.get(...) but getResourcesAsStream or its counterpart getResource:

try (Scanner scanner = new Scanner(MyClass.class.getResourceAsStream("/myfile.txt"))) {
  while (scanner.hasNextLine()) {
    System.out.println(scanner.nextLine());
  }
}

如果<$ c $找不到c> /myfile.txt 。

这篇关于在Eclipse中将Java项目的资源(图像,数据文件等)存储在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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