简体   繁体   中英

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: 控制台显示解决方案,因为一切实际运行

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: 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:

在此输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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