java从jar包中拷贝资源文件到临时文件夹

it2023-06-29  69

 具体方法:

/** * 拷贝资源问件 * * @param path */ public static void extract(String path) { try { //创建临时文件夹 File tempDir = createTempDir(); //拷贝资源文件到临时目录 copyLibToDir(tempDir, path); // 设置java.libray.path setLibraryPath(tempDir.getPath()); } catch (IllegalAccessException e) { log.error(e.getMessage(), e); } catch (NoSuchFieldException e) { log.error(e.getMessage(), e); } catch (IOException e) { log.error(e.getMessage(), e); } }

1.创建临时文件夹

/** * 创建临时文件夹 * * @return * @throws IOException */ public static File createTempDir() throws IOException { File tempDir = getTempDir(); boolean mkdirs = tempDir.mkdirs(); if (!tempDir.isDirectory()) { throw new IOException(); } else { tempDir.deleteOnExit(); } return tempDir; }

2.拷贝资源文件

在jar文件中,不能直接通过文件资源路径拿到文件,但是可以在jar包中拿到文件流。如果直接在idea中运行,是可以直接通过getFile获取文件进行拷贝

/** * 拷贝项目资源文件到系统临时目录 * * @param tempDir 临时目录 * @param tempDir 临时目录 */ private static void copyLibToDir(File tempDir, String path) { try { PathMatchingResourcePatternResolver rpr = new PathMatchingResourcePatternResolver(); //需要获取资源的路径 String name = String.format("classpath*:/%s/**/*.*", path); Resource[] resarr = rpr.getResources(name); //获得文件流,因为在jar文件中,不能直接通过文件资源路径拿到文件,但是可以在jar包中拿到文件流 for (Resource item : resarr) { InputStream in = item.getInputStream(); FileUtils.copyInputStreamToFile(in, new File(tempDir.getPath() + "\\" + item.getFilename())); in.close(); } } catch (IOException e) { log.error(e.getMessage(), e); } }

3.设置新的library.path

/** * 设置新的 java library path ,动态更改sys_paths, 使得usr_paths 重新初始化 * * @param path * @throws Exception */ public static void setLibraryPath(String path) throws IllegalAccessException, NoSuchFieldException { String oldPath = System.getProperty("java.library.path") + ";"; System.setProperty("java.library.path", oldPath + path); //set sys_paths to null MethodHandles.Lookup cl = MethodHandles.privateLookupIn(ClassLoader.class, MethodHandles.lookup()); VarHandle sys_paths = cl.findStaticVarHandle(ClassLoader.class, "sys_paths", String[].class); sys_paths.set(null); }

 

最新回复(0)