访问jar文件中打包的文档

发布于 2024-10-08 02:12:14 字数 305 浏览 0 评论 0原文

我试图获取打包为 jar 文件中资源的文档的文件路径,以便我可以在 swing 应用程序中显示它。当我从 eclipse 运行它时,我现在的方式是有效的,但是如果我将它导出到可运行的 jar 文件,我将无法访问打包在 jar 文件中的文档。当文档位于 jar 文件中时,如何获取文档的文件路径?

这是显示我如何尝试访问该文档的代码行:

File document = new File(getClass().getResource("/resources/documents/document.pdf").getPath());

Im trying to get the file path of a document that is packaged as a resource in a jar file so that i can display it in a swing application. The way I have it now works when I run it from eclipse but if I export it to a runnable jar file I can't access the the documents that are packaged in the jar file. How can I get the file path of the document when its inside the jar file?

Here is the line of code showing how I am trying to access the document:

File document = new File(getClass().getResource("/resources/documents/document.pdf").getPath());

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柒七 2024-10-15 02:12:14

JAR 文件中存在的唯一一种“文件路径”是相对于 JAR 根目录的路径。但就你而言,你似乎已经知道了(它是“​​/resources/documents/document.pdf”)。 JAR 文件内的文件没有可用于直接访问它们的路径,因为它们不存在于真实文件系统中。您需要使用 getResource() 或 getResourceAsStream() 来访问它们。我现在不记得 Swing 中的图像使用了哪些类,但仔细观察这些类 - 它们应该具有接受诸如 InputStream 或 URL 而不是文件路径之类的内容的重载方法。

The only kind of "file path" that exists for something inside a JAR file is the path relative to the root of the JAR. But in your case it seems that you know it already (it's "/resources/documents/document.pdf"). Files inside a JAR file have no path that you can use to access them directly as they don't exist within the real file system. You need to use either getResource() or getResourceAsStream() to access them. I don't remember right now which classes are used for images in Swing, but look closely at those classes - they should have overloaded methods that accept something like InputStream or URL instead of file path.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文