业务场景:其他应用需要使用我们提供的jar包完成一些功能,我们有些配置是放在jar包中,不好直接解压,所以把文件复制到本地之后,从中获取数据,如果后续有资源更新,可以直接放在该目录。
public static void copyJarResourceToLocal() throws URISyntaxException {
String localPath = System.getProperty("user.dir");
//获取本地的目录地址
Path resources = Paths.get(localPath, "resources");
URL jarURL = FileUtil.class.getProtectionDomain().getCodeSource().getLocation();
Path jarPath = Paths.get(jarURL.toURI());
//判断该文件是否是以jar结尾的文件
if (Files.isRegularFile(jarPath) && jarPath.toString().endsWith(".jar")){
try(JarFile jarFile = new JarFile(jarPath.toFile())){
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()){
JarEntry element = entries.nextElement();
String elementName = element.getName();
//获取文件路径
Path filePath = Paths.get(String.valueOf(resources), elementName);
//判断该文件中是否已经存在了该文件,如果不存在则拷贝
if (!Files.exists(filePath)){
//判断文件是不是以*.txt结尾的文件
if (elementName.endsWith(".txt") && !element.isDirectory()){
//写入到新目录中
try(InputStream inputStream = jarFile.getInputStream(element);
OutputStream outputStream = Files.newOutputStream(filePath)){
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) > 0){
outputStream.write(buffer, 0 ,len);
}
}
}
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
目录结构为: