java中图片存放在哪里,在Eclipse中将Java项目的资源(图像,数据文件等)存储在哪里?...

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

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.

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).

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?

解决方案

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

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

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 would compile all Java into target/classes and copy all resources into target/classes. For test, it would be target/test-classes.

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());

}

}

This would probably throw a NPE if /myfile.txt was not found.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值