需要解压的文件类型为zip
此代码经过项目实战,有问题可以评论
public static void decompressionZIp(String zipPath,String saveFilePath){
try (FileInputStream fileIo = new FileInputStream(zipPath);
ZipInputStream zipFileIo =
new ZipInputStream(new BufferedInputStream(fileIo ))) {
ZipEntry entry;
//当读取不到文件时结束
while ((entry = zis.getNextEntry()) != null) {
int size;
byte[] buffer = new byte[2048];
//entry.getName() 此时解压文件的名称
//如果你解压的文件名称不是你想要 你可以自定义
//zip包的第一个文件名:a.pdf
//你需要的文件名称:b,.pdf
//File fileOut = new File(saveFilePath+"\\b.pdf"); 此时zip包里只能有一个文件 不然会被覆盖
//得到正确自己需要的文件需要自己根据实际情况设置文件名称
File fileOut = new File(saveFilePath+"\\"+entry.getName());
try (
FileOutputStream fos = new FileOutputStream(fileOut);
BufferedOutputStream bos = new BufferedOutputStream(fos, buffer.length)) {
//当读取到没有的时候结束
while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
//将读取到的内容写进你保存的路径内
bos.write(buffer, 0, size);
}
bos.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
文件复制
public static void copyFile(String inPath,String outPath){
//输入和输出流
FileInputStream fileInputStream = new FileInputStream(inPath);
FileOutputStream fileOutputStream = new FileOutputStream(outPath);
//数据接收数组
byte[] b = new byte[1024];
//-1代表没有可读写的数据
while (fis.read(b)!=-1)
{
fos.write(b);
}
//释放资源
fis.close();
fos.close();
}
文件夹压缩成zip
public static void compress(String srcPath , String dstPath) throws Exception{
//srcPath 为路径 dstPath 为压缩之后的路径 这个方法直接使用必须按照举例参数
//srcPath D:/bill/copy/test/testFile/ 最后/必须带 不然会认为是test文件夹中的testFile文件
//srcPath D:/bill/copy/result/testFile.zip
File srcFile = new File(srcPath);
File dstFile = new File(dstPath);
if (!srcFile.exists()) {
throw new FileNotFoundException(srcPath + "不存在!");
}
FileOutputStream out = null;
ZipOutputStream zipOut = null;
try {
out = new FileOutputStream(dstFile);
CheckedOutputStream cos = new CheckedOutputStream(out,new CRC32());
zipOut = new ZipOutputStream(cos);
String baseDir = "";
compress(srcFile, zipOut, baseDir);
}
finally {
if(null != zipOut){
zipOut.close();
out = null;
}
if(null != out){
out.close();
}
}
}
1254



被折叠的 条评论
为什么被折叠?



