package ccc.my;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Juneibulei {
public static void main(String[] args) {
hh();
}
public static void hh() {
File nihao2 = new File("E:\\明日科技教程\\java视频\\");// 源文件
File nihao = new File("D:\\WODW.zip");// 压缩包目录
ZipOutputStream ya = null;
try {
ya = new ZipOutputStream(new FileOutputStream(nihao));// 创建zip输出流用来写入读取源文件的数据,实现压缩
if (nihao2.isDirectory()) {
for (File v : nihao.listFiles()) {
yashou(ya, v,new StringBnffer(""));
ysbml = new StringBuffer("");
} else {
yashou(ya, nihao2,new StringBuffer(""));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
ya.close();//此方法执行完,关闭ya释放资源
} catch (IOException e) {
e.printStackTrace();
}
}
}
static void yashou(ZipOutputStream ya, File v,StringBuffer ysbml) {
FileInputStream xie = null;
if (v.isFile()) {
try {
xie = new FileInputStream(v);
byte[] hcq = new byte[1234]; // 定义xie的字节缓冲区
int b = -1; // 用来获取写入hcq的长度,范围在0~1233
ya.putNextEntry(new ZipEntry(ysbml + v.getName()));// 在压缩包或条目中新建目录
while ((b = xie.read(hcq)) != -1) {
ya.write(hcq, 0, b);//因为当读到尾是数据最后字节数据可能不满1234个,就采用此方法
ya.finish();// 刷新操作
}
ya.closeEntry();// 关闭此条目,因为此条目已写入数据
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
for (File vv : v.listFiles()) {
yashou(ya, vv);
ysbml.append(vv.getName() + File.separator);
}
}
try {
xie.close();//当此方法运行结束时关闭xie
} catch (IOException e) {
e.printStackTrace();
}
}
}//自己仿照课程、sl的历程、视频教程的逻辑复写的感觉逻辑好想没问题但总是抛出异常
异常信息:Exception in thread "main" java.lang.NullPointerException
at ccc.my.Juneibulei.hh(Juneibulei.java:24)
at ccc.my.Juneibulei.main(Juneibulei.java:14)