访问 JAR 文件时出现 NotDirectoryException

NotDirectoryException while acessing a JAR file

晚上好,

我正在尝试动态访问包含几个 *.class 文件的 JAR 文件。 我读过它,一个好方法是使用 java class 文件系统访问 jar 中的几个文件。我写了以下代码:

private void loadJar(String gameName) {
        final String packageBinaryName = gameName;
        final String pathname = packageBinaryName.replace(".", "/") +".jar";
        URI uri = null;
        uri = new File(pathname).toURI();//.toURL();
        final String[] array = uri.toString().split("!");
        FileSystem fs = null;
        Path dir;

        try 
        {
            if(array.length == 2) 
            {
                final Map<String, String> env = new HashMap<>();
                fs = FileSystems.newFileSystem(URI.create(array[0]), env);
                dir = fs.getPath(array[1]);   
            } 
            else
                dir = Paths.get(uri);

            DirectoryStream<Path> stream;

            System.out.println(dir);
            stream = Files.newDirectoryStream(dir, "*.class");
        }
        catch (IOException e) 
        {
            e.printStackTrace();
        }
}

但是我得到了 java.nio.file.NotDirectoryException

JAR 文件存在并且指向写入路径。可能导致此问题的原因是什么?

目录打印以下内容:

C:\Users\afonso\workspace\GameEvaluatorDummy\src\TicTacToe.jar

编辑:请注意,调试 dir 语句会在 else 语句中获取其值

dir=Paths.get(uri);

当然是到else路径了
您正在检查的 URI 永远不会包含感叹号。
但只是 JAR 文件的 URI。
除非您将带有感叹号的内容作为此方法的参数,否则我会说这也行不通。

你追求的是

FileSystem fs = FileSystems.newFileSystem(new URI("jar:file:///path/to/the.jar"), Collections.<String,?>emptyMap());
Path dir = fs.getPath("/");
Files.newDirectoryStream(dir, "*.class*);

但请注意,这不会自动递归到子目录中。