Java:导出到 JAR 后路径名不起作用
我已经将一个项目导出到 eclipse 中的可运行 JAR 中。我的代码中有几个地方完成了以下操作。
String file = "src/Files/...";
loadFile(file); // purely for example
现在该项目采用 JAR 形式,这些目录似乎不存在并且加载这些文件失败。我非常确定我引用的文件已打包在 JAR 中。导出到 JAR 时目录是否会以任何特定方式发生变化?关于如何实现这项工作还有其他想法吗?
I have exported a project to a runnable JAR in eclipse. There are a few places in my code where I've done the following.
String file = "src/Files/...";
loadFile(file); // purely for example
Now that the project is in the form of a JAR, those directories don't seem to exist and loading those files fails. I'm pretty sure that the files I'm referencing are packed in the JAR. Do the directories change in any particular way when exported to JAR? Any other ideas on how to make this work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将它们视为类路径资源,而不是本地磁盘文件系统路径。当您将文件打包在 JAR 中并且您也不希望依赖于工作目录时,这将不起作用。 JAR 内的文件已经是类路径的一部分。
假设您在
com.example
包中有一个foo.txt
文件,那么您可以按如下方式获取它的InputStream
或者当您在
static
上下文中或者当您想要扫描全局类路径时
另请参阅:
You need to treat them as a classpath resource, not as a local disk file system path. This isn't going to work when you package the files in a JAR and you also don't want to be dependent on the working directory. Files inside a JAR are part of the classpath already.
Assuming that you've a
foo.txt
file in packagecom.example
, then you can get anInputStream
of it as followsOr when you're inside
static
contextOr when you want to scan the global classpath
See also: