开发者

Accessing Data inside of a .jar

I am currently putting a program into a .jar, and have difficulties telling it where to get its data from. The data was inside of a file in the project, and I am sure that it is located in the jar as well. But I have no clue on how to get a path into a jar.

I found the getClass().getClassLoader().getResourceAsStream() method 开发者_运维问答online to get an input stream into the jar, but since I used FileReaders all the time, I dont know what to do with it as well..

I`d be very thankful for any help.

Edit:

Here is a picture of how the directory is organized:

Accessing Data inside of a .jar

My command window shows what happens if I run the .jar. Nullpointer in line 30. I tried it with and without .getClassLoader(), it just wont find it. Here is the inside of the jar:

Accessing Data inside of a .jar

again, app is where the class files are in. Hence, via class.getResource.. I should be able to search in DataPackeg. Man, this is wearing me out.


A key concept to understand is that files don't exist inside of jars. You must instead get your data as a read-only resource, and you will need to use a path that is relative to path of your class files.

If you're still stuck, you may need to tell us more specifics about your current program, its structure, what type of data you're trying to get, where it's located in the jar file, and how you're trying to use it.

For instance, say your package structure looked like this:

Accessing Data inside of a .jar

So the class file is located in the codePackage package (this is Eclipse so the class files live in a universe parallel to the java files), and the resource's location is in the codePackage.images package, but relative to the class file it is the images directory, you could use the resource like so:

package codePackage;

import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;

public class ClassUsesResources {
   private JLabel label = new JLabel();

   public ClassUsesResources() {
      try {
         BufferedImage img = ImageIO.read(getClass().getResourceAsStream(
               "images/img001s.jpg"));
         ImageIcon icon = new ImageIcon(img);
         label.setIcon(icon);

         JOptionPane.showMessageDialog(null, label);
      } catch (IOException e) {
         e.printStackTrace();
         System.exit(-1);
      }
   }

   public static void main(String[] args) {
      new ClassUsesResources();
   }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜