简体   繁体   中英

How to get the path of file when make a jar file in Java

I am building a game in java and everything works just fine when I run it in intellij idea with no error .

The problem start when i build my project as jar file.

I have this method :

public void addImageOfObject(String add, String dir, ArrayList<ImageIcon> linkedList, Dimension size) {
    Image image;
    String dirc;
    File file = null;
    try {
        file = new File(classLoader.getResource(dir).getFile());
    } catch (Exception e) {
        JOptionPane.showMessageDialog(StaticVariables.mainClass, e.getStackTrace());
    }
    try {
        for (int i = 0; file.listFiles().length > i; i++) {
            try {
                dirc = dir + i + ".png";
                image = loadImage(dirc);
                linkedList.add(new ImageIcon(image.getScaledInstance(size.width, size.height, 4)));
            } catch (Exception e) {
                JOptionPane.showMessageDialog(StaticVariables.mainClass, e.getStackTrace());
                e.printStackTrace();
            }

        }

    } catch (Exception e) {
        JOptionPane.showMessageDialog(StaticVariables.mainClass, e.getStackTrace());
        JOptionPane.showMessageDialog(StaticVariables.mainClass, "file not found ");
    }
}

This is the class loader :

ClassLoader classLoader = ClassLoader.getSystemClassLoader();

I can't get the right path of the file ..when i run it in jar file its give an error file not found on :

file = new File(classLoader.getResource(dir).getFile()); 

I call to method with this line :

imageLoader.addImageOfObject("src/main/java/","ImageHandel/Photos/character/male/attack/down/",aMale,new Dimension(500,400));

This is the path of files

在此处输入图片说明

The number of files I want to get file.listFiles()

在此处输入图片说明

In the male folder there is 44 files .. that's the number I want to get in order to run on the loop 44 time and i just can't find the right way to do it! I tried a lot of thing but nothing help me ..

Have any idea what is the problem ?

Simply you can create folder on location where your running jar file,

ImageHandel/Photos/character/male/attack/down/

Run it in jar file by considering that location.

use to add static folder for serving images eg In spring boot we can configure static folder as follows:

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/ImageHandel/**")
            .addResourceLocations("file:ImageHandel/")
            .setCachePeriod(0);
}

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