我的项目如何访问其“资源”目录在Eclipse和Maven打包的jar文件中运行时? [英] How can my project access its "resources" directory both when run in Eclipse and from a Maven-packaged jar file?

查看:397
本文介绍了我的项目如何访问其“资源”目录在Eclipse和Maven打包的jar文件中运行时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Eclipse中的Maven项目(在m2e插件的帮助下)。当我将项目打包到jar文件(mvn install)中时,资源中的所有文件都位于jar的根目录。



因此,在我的程序中仅使用裸文件名:

 文件文件=新文件(foo.txt); 

但是当我通过Eclipse构建和运行我的项目时,我必须使用相对路径文件:

 文件文件=新文件(src / main / resources / foo.txt); 

我该怎么办来解决这个问题?

解决方案

要访问程序的资源,请不要使用文件 FileInputStream 和类似的类。
它们不适用于jar文件内的任何东西。



而是使用 Foo.class.getResource(...) .getResourceAsStream()来访问您的资源。 (在这样做之前阅读文档。)



我不知道从eclipse开始的程序是否可以访问这些 - 请尝试回报!


I'm working with Maven project in Eclipse (with help of m2e plugin). When I pack my project into jar-file (mvn install), all files from "resources" are located in the root of jar.

Therefore, in my program I should use only bare file names:

File file = new File("foo.txt");

But when I build and run my project by Eclipse, I would have to use the relative path to the file:

File file = new File("src/main/resources/foo.txt");

What should I do to solve this problem?

解决方案

To access your program's resources, don't use File, FileInputStream and similar classes. They will not work for anything inside a jar file.

Instead, use Foo.class.getResource(...) or .getResourceAsStream() to access your resources. (Read the documentation before doing so.)

I'm not sure if a program started from eclipse can access these - please try and report back!

这篇关于我的项目如何访问其“资源”目录在Eclipse和Maven打包的jar文件中运行时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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