开发者

How to access my applications' resources inside a runnable jar?

开发者 https://www.devze.com 2023-03-29 22:08 出处:网络
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 w

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 开发者_JAVA技巧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!


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

BufferedImage bufImg = ImageIO.read(MyClass.class.
         getResourceAsStream("img/anImage.png"));

Just be sure to use a path relative to the class file location and your actual class name, or this.getClass()

0

精彩评论

暂无评论...
验证码 换一张
取 消