获取文件 jar和本地的不同

String path= packageName.replaceAll("\\.","/");
        URL url = this.getClass().getClassLoader().getResource(path);
        System.out.println(url);
        if(url==null)
        {
            return;
        }
        // 得到协议的名称
        String protocol = url.getProtocol();

        // 如果是以文件的形式保存在服务器上
        if ("file".equals(protocol)) {
            // 以文件的方式扫描整个包下的文件 并添加到集合中
            String filePath="";
            try {
                filePath= java.net.URLDecoder.decode(url.getPath(),"utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            File classDir = new File(filePath);
            for (File file : classDir.listFiles()){
                System.out.println(file);
                if(file.isDirectory()){
                    doScanner(packageName + "." +file.getName(),serviceNames);
                }else {
                    serviceNames.add(packageName + "." + file.getName().replace(".class",""));
                }
            }
        } else if ("jar".equals(protocol)) {
            // 如果是jar包文件
            // 定义一个JarFile
            JarFile jar;
            // 获取jar
            try {
                jar = ((JarURLConnection) url.openConnection())
                        .getJarFile();
                // 从此jar包 得到一个枚举类
                Enumeration<JarEntry> entries = jar.entries();
                // 同样的进行循环迭代
                while (entries.hasMoreElements()) {
                    // 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
                    JarEntry entry = entries.nextElement();
                    String name = entry.getName();
                    if (name.indexOf(path + "/") >= 0&&!name.replace(path + "/","").isEmpty()){
                        serviceNames.add(packageName + "." + name.replace(".class", "").replace(path + "/", ""));
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

猜你喜欢

转载自blog.csdn.net/qq_36120342/article/details/88182453