一、打压缩包的方法
文件上传我就不在多做描述了,又不懂的可以看我的文件上传那篇文章。
这里我直接就给出打包的方法。
/**
* TODO: 打成压缩包
* UPLOAD_URL 带压缩的文件目录
* TAR_FILE_PATH 指定打成的tar包的名称和tar包存放的位置
* @param name 压缩的文件名
*/
private static void toCompress(String name){
FileOutputStream dest = null;
TarOutputStream tarOut = null;
try {
//设置tar包位置
dest = new FileOutputStream(TAR_FILE_PATH + name + ".tar");
tarOut = new TarOutputStream(new BufferedOutputStream(dest));
//设置待打包源文件的位置
File sourceFile = new File(UPLOAD_URL);
//listFiles是获取该目录下所有文件和目录的绝对路径
File[] sourceFiles = sourceFile.listFiles();
if (sourceFiles != null) {
for (File f : sourceFiles) {
tarOut.putNextEntry(new TarEntry(f, f.getName()));
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
int count;
byte[] data = new byte[2048];
//将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此缓冲的输出流。
//public void write(byte[] b,int off,int len);
//从此字节输入流中给定偏移量处开始将各字节读取到指定的 byte 数组中。
//public int read(byte[] b,int off,int len);
while ((count = bis.read(data)) != -1) {
// write(byte[] wBuf, int wOffset, int numToWrite)
// 将字节写入当前的tar存档条目。
tarOut.write(data, 0, count);
}
tarOut.flush();
bis.close();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (tarOut != null){
tarOut.close();
}
if (dest != null){
dest.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
这是打包的方法,我这里是打成了.tar压缩包。
二、配置和读取压缩路径。
首先我们在配置文件中加入一下配置。
# 配置图片访问路径
upload-url: D:/img/
# 压缩文件存放路径
tarFilePath: D:/test/
然后我们读取配置,由于static修饰,@Value不能直接注入,我选择用静态代码块进行读取。
/**UPLOAD_URL 带压缩的文件目录和文件上传路径*/
public static String UPLOAD_URL;
/**指定打成的tar包的名称和tar包存放的位置*/
public static String TAR_FILE_PATH;
// 读取yml里的属性值
static {
YamlPropertiesFactoryBean yamlMapFactoryBean = new YamlPropertiesFactoryBean();
//可以加载多个yml文件
yamlMapFactoryBean.setResources(new ClassPathResource("application.yml"));
Properties properties = yamlMapFactoryBean.getObject();
//获取yml里的路径参数
if (properties != null) {
UPLOAD_URL = properties.getProperty("upload-url");
TAR_FILE_PATH = properties.getProperty("tarFilePath");
if (UPLOAD_URL == null || "".equals(UPLOAD_URL)){
throw new RuntimeException("上传路径为空");
}
if (TAR_FILE_PATH == null || "".equals(TAR_FILE_PATH)){
throw new RuntimeException("压缩路径为空");
}
}else {
throw new RuntimeException("找不到名为application.yml配置文件");
}
//上传路径
File targetFile = new File(UPLOAD_URL);
//如果路径不存在就创建
if (!targetFile.exists()) {
targetFile.mkdirs();
}
}
最后在你先要压缩的时候调用这个方法就好,如果还是看不明白,可以到我完整的工具类中查看所有代码。
三、完整的工具类链接
https://blog.csdn.net/han_zheng_yiqi/article/details/108243512
感谢观看。