How to list the files inside a JAR file?

前端 未结 16 2240
温柔的废话
温柔的废话 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:37

    Code that works for both IDE's and .jar files:

    import java.io.*;
    import java.net.*;
    import java.nio.file.*;
    import java.util.*;
    import java.util.stream.*;
    
    public class ResourceWalker {
        public static void main(String[] args) throws URISyntaxException, IOException {
            URI uri = ResourceWalker.class.getResource("/resources").toURI();
            Path myPath;
            if (uri.getScheme().equals("jar")) {
                FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap());
                myPath = fileSystem.getPath("/resources");
            } else {
                myPath = Paths.get(uri);
            }
            Stream walk = Files.walk(myPath, 1);
            for (Iterator it = walk.iterator(); it.hasNext();){
                System.out.println(it.next());
            }
        }
    }
    

提交回复
热议问题