eclipse 和 JAR 中的资源位置差异问题
我编写了一个完全基于单个文本文件的程序:我读取文件,存储信息,然后搜索信息等。因此,为了使程序正常工作,文件只需存在并可由程序检测到。 我使用eclipse,所以我把文件放在默认的资源映射(src/main/resources)中。在程序开始时,我创建文件:
private static File textFile = new File("src/main/resources/TEXT.TXT")
但是,当我尝试使用 Maven 打包程序时,我得到一个 JAR,其中所有类和资源文件都存在于同一文件夹中;我的程序停止工作,因为它找不到该文件了。
关于如何处理这个问题有什么帮助吗?我更喜欢我的程序在 Eclipse 中运行并作为 JAR 运行的情况,但仅作为 JAR 也可以。
I wrote a program that is based completely on a single text file: I read the file, store the information, then search the information, etc. So, for the program to work, the file just has to be present and detectable by the program.
I use eclipse, so I put the file is in the default resources map (src/main/resources). At the start of my program I create the file:
private static File textFile = new File("src/main/resources/TEXT.TXT")
However, when I try to package my program using Maven, I get a JAR in which all class and resources files are present in the same folder; my program stops working since it cannot find the file anymore.
Any help on how to deal with this problem? I`d prefer a situation in which my program works in eclipse and as a JAR, but as a JAR only would be alright as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 ClassLoader.getResourceAsStream 从类路径加载它(或 getResource 获取文件的 URL)。
只要 src/main/resources 位于 Eclipse 中的类路径上,此操作就有效。 (maven eclipse 插件默认包含它。)该文件必须位于 jar 文件中才能在 eclipse 之外工作。
You can use ClassLoader.getResourceAsStream to load it from the classpath (or getResource to get the URL of the file).
This works as long as src/main/resources is on the classpath in eclipse. (The maven eclipse plugin includes it by default.) The file has to be in the jar file to work outside of eclipse.
很好的建议,这在 Eclipse 本身中完美运行:返回文件的正确位置,我可以使用该文件做任何我喜欢的事情。
当以jar的形式打开程序时,仍然存在问题。 getResource 方法返回一个看起来像正确位置的位置:
/something/something/something/something/workspace/program/target/program-0.0.1.jar!/TEXT.TXT。
但是,当我将此 url 转换为字符串,使用该字符串创建文件对象并在程序中使用此文件对象时,出现以下错误:
java.io.FileNotFoundException: file:/something/something/something/ some/workspace/program/target/program-0.0.1.jar!/TEXT.TXT (没有这样的文件或目录)
所以, getResource 方法确实找到了该文件,但程序不知何故无法使用它..
Nice suggestions, this works perfect in eclipse itself: the correct location of the file is returned and I can use the file to do whatever I like.
When opening the program as a jar, there is still a problem. The getResource method returns a location that looks like the right one:
/something/something/something/something/workspace/program/target/program-0.0.1.jar!/TEXT.TXT.
However, when I convert this url to a string, use that string to create a file object and use this file object in my program, I get the following error:
java.io.FileNotFoundException: file:/something/something/something/something/workspace/program/target/program-0.0.1.jar!/TEXT.TXT (No such file or directory)
So, the getResource method does find the file, but the program somehow can't use it..