Getting a directory inside a .jar

后端 未结 8 1497
悲哀的现实
悲哀的现实 2020-12-11 04:48

I am trying to access a directory inside my jar file. I want to go through every of the files inside the directory itself. I tried, for example, using the following:

<
8条回答
  •  死守一世寂寞
    2020-12-11 05:13

    You can use the PathMatchingResourcePatternResolver provided by Spring.

    public class SpringResourceLoader {
    
        public static void main(String[] args) throws IOException {
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    
            // Ant-style path matching
            Resource[] resources = resolver.getResources("/Images/**");
    
            for (Resource resource : resources) {
                System.out.println("resource = " + resource);
                InputStream is = resource.getInputStream();
                BufferedImage img =  ImageIO.read(is);
                System.out.println("img.getHeight() = " + img.getHeight());
                System.out.println("img.getWidth() = " + img.getWidth());
            }
        }
    }
    

    I didn't do anything fancy with the returned Resource but you get the picture.

    Add this to your maven dependency (if using maven):

    
        org.springframework
        spring-core
        3.1.2.RELEASE
    
    

    This will work directly from within Eclipse/NetBeans/IntelliJ and in the jar that's deployed.

    Running from within IntelliJ gives me the following output:

    resource = file [C:\Users\maba\Development\stackoverflow\Q12016222\target\classes\pictures\BMW-R1100S-2004-03.jpg]
    img.getHeight() = 768
    img.getWidth() = 1024
    

    Running from command line with executable jar gives me the following output:

    C:\Users\maba\Development\stackoverflow\Q12016222\target>java -jar Q12016222-1.0-SNAPSHOT.jar
    resource = class path resource [pictures/BMW-R1100S-2004-03.jpg]
    img.getHeight() = 768
    img.getWidth() = 1024
    

提交回复
热议问题