How to list the files inside a JAR file?

前端 未结 16 2460
温柔的废话
温柔的废话 2020-11-22 00:40

I have this code which reads all the files from a directory.

    File textFolder = new File(\"text_directory\");

    File [] texFiles = textFolder.listFiles         


        
16条回答
  •  不知归路
    2020-11-22 01:38

    A jar file is just a zip file with a structured manifest. You can open the jar file with the usual java zip tools and scan the file contents that way, inflate streams, etc. Then use that in a getResourceAsStream call, and it should be all hunky dory.

    EDIT / after clarification

    It took me a minute to remember all the bits and pieces and I'm sure there are cleaner ways to do it, but I wanted to see that I wasn't crazy. In my project image.jpg is a file in some part of the main jar file. I get the class loader of the main class (SomeClass is the entry point) and use it to discover the image.jpg resource. Then some stream magic to get it into this ImageInputStream thing and everything is fine.

    InputStream inputStream = SomeClass.class.getClassLoader().getResourceAsStream("image.jpg");
    JPEGImageReaderSpi imageReaderSpi = new JPEGImageReaderSpi();
    ImageReader ir = imageReaderSpi.createReaderInstance();
    ImageInputStream iis = new MemoryCacheImageInputStream(inputStream);
    ir.setInput(iis);
    ....
    ir.read(0); //will hand us a buffered image
    

提交回复
热议问题