如何访问我的应用程序?可运行的 jar 内的资源?
我刚刚发布了这个问题:如何分发我的 Java 程序,使其可以通过双击单个文件来运行?我让可运行的 jar 正常工作,但很多事情都没有按照我希望的方式工作,因为我的程序找不到我想要使用的资源,例如图像和 SQLite 数据库文件。
在我的文件系统中,img 文件夹中有几个 .png 图像,项目根文件夹中有一个名为 test.db 的数据库
当我的项目位于 Eclipse 中时,我使用以下方式访问我的图像:
BufferedImage bufImg = ImageIO.read(new File("img/anImage.png"))
我连接到我的 SQLite 数据库使用:
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:test.db");
现在,当我双击新创建的 runnable-jar 时,找不到资源。我想知道我应该如何访问它们并让我的程序在不在 IDE 中时运行。
我还想知道如何查看例外情况(如果可能的话)。因为现在,某些页面保持灰色,因为它们无法加载,因为(我猜测)无法找到某些资源,但我不知道是否只是数据库导致了问题,或者是否也是图像。
非常感谢并抱歉在这么短的时间内提出两个相关问题!
I just posted this question: How to distribute my Java program so that it is runnable by double-clicking a single file? and while I got the runnable jar working, many things don't work the way I'd want them to since my program cannot find the resources I want to use such as images and a SQLite database file.
In my file system, I have several .png images in the img folder and a database located at the project's root folder named test.db
While my project was in Eclipse, I accessed my images using something like:
BufferedImage bufImg = ImageIO.read(new File("img/anImage.png"))
And I connected to my SQLite database using:
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:test.db");
Now, when I double-click my newly created runnable-jar, the resources cannot be found. I'd like to know how I'm supposed to access them and have my program work when it is not in a IDE.
I would also like to know how I can see what the exceptions are (if at all possible). Because right now, some pages stay gray because they don't load because (I'm guessing) some resources cannot be found, but I have no idea if it's only the database that is causing a problem or if it's also the images.
Thanks a ton and sorry for asking two related questions in such a small timeframe!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Jar 中没有文件,只有资源,因此大多数使用文件的方法也将接受资源。
例如 ImageIO.read(...) 有一个接受 URL 的重载和一个接受 InputStream 的重载。因此,请尝试
确保使用相对于类文件位置和实际类名的路径,或
this.getClass()
There are no Files within a Jar, only resources, so most methods that use files will also accept resources.
For instance ImageIO.read(...) has an overload that accepts URL and one that accepts InputStream. So try
Just be sure to use a path relative to the class file location and your actual class name, or
this.getClass()