简体   繁体   English

访问打包在jar文件中的文档

[英]Accessing documents packaged in a jar file

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. 我正在尝试获取打包为资源的jar文件中文档的文件路径,以便我可以在swing应用程序中显示它。 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. 从Eclipse运行它时,现在可以使用它的方式,但是如果将其导出到可运行的jar文件中,则无法访问jar文件中打包的文档。 How can I get the file path of the document when its inside the jar file? 当文件放在jar文件中时,如何获取文件的文件路径?

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

The only kind of "file path" that exists for something inside a JAR file is the path relative to the root of the JAR. 对于JAR文件中某些内容而言,唯一存在的“文件路径”是相对于JAR根目录的路径。 But in your case it seems that you know it already (it's "/resources/documents/document.pdf"). 但是就您而言,您似乎已经知道了(它是“​​ /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. JAR文件中的文件没有路径可用于直接访问它们,因为它们在实际文件系统中不存在。 You need to use either getResource() or getResourceAsStream() to access them. 您需要使用getResource()或getResourceAsStream()来访问它们。 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. 我现在不记得在Swing中哪些类用于图像,但请仔细查看这些类-它们应该具有重载的方法,这些方法接受InputStream或URL之类的东西而不是文件路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM