读取Jar包下的资源文件以及指定文件的解决方案

Jar文件是一种归档文件,里面包含了一堆Class文件,以及Resouce文件,File是文件资源的统称

Jar file的结构,包含了META-INT,properites,以及resource资源。
image

普通获取一个文件的方式为:
File file = new File(path)
这在文件系统中,运行起来的是没有问题。

但当你的代码以Jar的方式去运行的时候,
Resources作为源文件打包后其下的文件直接会被存放到classes下,
很可能会抛出一个Exception
cannot be resolved to absolute file path because it does not reside in the file system:jar:file:
或者是FileNotFindExpcetion

这里有两个需求:
读取资源文件,读取指定文件(Class)

第一种:如果你是获取资源文件,将其转为InputStream,直接在系统临时目录生成一个临时文件,等到使用完毕之后可以自行决定要不要删除。
为了方便,可以将resource下面的资源文件在Server启动的时候全部copy到临时目录

InputStream path = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
copyInputStreamToFile(path, dstFile);



private static void copyInputStreamToFile(InputStream inputStream, File file) throws IOException {
    try (OutputStream  outputStream =  Files.newOutputStream(file.toPath())) {
        FileCopyUtils.copy(inputStream, outputStream);
    }
}

第二种:如何在Jar里面读取指定的文件?

加载Class到HashSet

public static Set<Class> findClassesByJar(String pathToJar) throws IOException, ClassNotFoundException {
        JarFile jarFile = new JarFile(pathToJar);
        Enumeration<JarEntry> e = jarFile.entries();

        URL[] urls = { new URL("jar:file:" + jarFile + "!/") };
        URLClassLoader cl = URLClassLoader.newInstance(urls);

        Set<Class> classes = new HashSet<>();
        while (e.hasMoreElements()) {
            JarEntry jarEntry = e.nextElement();
            if (jarEntry.isDirectory() || !jarEntry.getName().endsWith(".class")) {
                continue;
            }

            // -6 because of .class
            String className = jarEntry.getName().substring(0, jarEntry.getName().length() - 6);
            className = className.replace('/', '.');
            Class c = cl.loadClass(className);
            classes.add(c);
        }

        return classes;
    }

将Class文件同样拷贝到临时目录
然后利用File file new File(path) 读取

public static void copyClassToDir(String jarFile) throws  IOException {
        JarFile jar = new JarFile(jarFile);
        java.util.Enumeration enumEntries = jar.entries();
        while (enumEntries.hasMoreElements()) {
            java.util.jar.JarEntry file = (java.util.jar.JarEntry) enumEntries.nextElement();
            
                        //Nedd set temp folder
            java.io.File f = new java.io.File(DEFAULT_TMP_DIR_PATH + "/" + file.getName());
            if (file.isDirectory()) {
                // if its a directory, create it
                f.mkdir();
                continue;
            }
            
            java.io.InputStream is = jar.getInputStream(file);
            // get the input stream
            java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
            while (is.available() > 0) {
                // write contents of 'is' to 'fos'
                fos.write(is.read());
            }

            fos.close();
            is.close();
        }

    }

评论

暂无评论