2023年12月2日发(作者:)
java如何读取jar包内资源文件_读取Jar包下的资源文件以及指定文件的解决方案...Jar文件是一种归档文件,里面包含了一堆Class文件,以及Resouce文件,File是文件资源的统称Jar file的结构,包含了META-INT,properites,以及resource资源。普通获取一个文件的方式为:File file = new File(path)这在文件系统中,运行起来的是没有问题。但当你的代码以Jar的方式去运行的时候,Resources作为源文件打包后其下的文件直接会被存放到classes下,很可能会抛出一个Exceptioncannot 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 =tThread().getContextClassLoader().getResourceAsStream(filePath);copyInputStreamToFile(path, dstFile);private static void copyInputStreamToFile(InputStream inputStream, File file) throws IOException {try (OutputStream outputStream = putStream(())) {(inputStream, outputStream);}}第二种:如何在Jar里面读取指定的文件?加载Class到HashSetpublic static Set findClassesByJar(String pathToJar) throws IOException, ClassNotFoundException {JarFile jarFile = new JarFile(pathToJar);Enumeration e = s();URL[] urls = { new URL("jar:file:" + jarFile + "!/") };URLClassLoader cl = tance(urls);Set classes = new HashSet<>();while (eElements()) {JarEntry jarEntry = ement();if (ctory() || !e().endsWith(".class")) {continue;}// -6 because of .classString className = e().substring(0, e().length() - 6);className = e('/', '.');Class c = ass(className);(c);}return classes;}将Class文件同样拷贝到临时目录然后利用File file new File(path) 读取public static void copyClassToDir(String jarFile) throws IOException {JarFile jar = new JarFile(jarFile);ation enumEntries = s();while (eElements()) {ry file = (ry) ement();//Nedd set temp f = new (DEFAULT_TMP_DIR_PATH + "/" + e());if (ctory()) {// if its a directory, create ();continue;}tream is = utStream(file);// get the input tputStream fos = new tputStream(f);while (ble() > 0) {// write contents of 'is' to 'fos'(());}();();}}


发布评论