压缩流ZipOutStream ---- 求帮忙看一下代码,为什么压缩后都是乱码,解压出来的都是Null字符,感觉自己的逻辑没什么么错

嗯嗯** 2019-11-23 09:16:14

/**
* 参数:传入需要压缩文件的绝对路径
*/
public static void compress(String sourcePath) {

try {
// 1. 创建一个压缩流、并且如果没有关联的压缩文件,自动创建 -- 压缩后的文件在桌面上
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("C:\\Users\\lrc\\Desktop\\压缩.zip"));
BufferedOutputStream bos = new BufferedOutputStream(zos);
// 2. 将即将压缩的文件名转为 File对象
File f = new File(sourcePath);

// 3. 调用递归函数
zipFile(zos, bos, f, f.getName());

// 4. 压缩输出流关闭
bos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

public static void zipFile(ZipOutputStream zos, BufferedOutputStream bos, File f, String prefix) throws IOException {

// 1. 获取当前File对象 是文件 则返回null 是目录则返回File数组
File[] files = f.listFiles();

// 2. 文件压缩
if (files == null) {
zos.putNextEntry(new ZipEntry(prefix));
InputStream is = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(is);
byte[] buffer = new byte[2048];
int len = -1;
while ((len = bis.read()) != -1) {
bos.write(buffer, 0, len);
}
bis.close();
// 3. 空目录压缩
} else if(files.length == 0) {
zos.putNextEntry(new ZipEntry(prefix + "\\"));

// 4. 目录内各个文件的压缩
} else {
for (File file : files) {
zipFile(zos, bos, file, prefix + "\\" + file.getName());
}
}
}


...全文
252 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
嗯嗯** 2019-11-24
  • 打赏
  • 举报
回复

62,625

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧