您的位置:首页 > 编程语言 > Java开发

java解压文件

2016-08-07 22:09 183 查看
需求:从本地上传一个.zip的文件夹,文件夹中的文件是一些图片,解压到服务器的某个路径。

package com.it.test;

import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
* Created by lingmao on 2016/8/7.
*/
public class UnZipFile {
public static void main(String[] args) throws IOException {

/**
* 解压文件
*/
try {
File zipFile = new File("C:/Users/lingmao/Desktop/photo/photo.zip");
String path = "e:/test/";
unZipFiles(zipFile, path);
}
catch (Exception e){
System.out.print(e.getMessage());
}
}

/**
* 解压文件到指定目录
* @param zipFile
* @param descDir
* @author isea533
*/
@SuppressWarnings("rawtypes")
public static void unZipFiles(File zipFile,String descDir)throws IOException{
File pathFile = new File(descDir);
if(!pathFile.exists()){
pathFile.mkdirs();
}
//        如果文件的名字有中文,需要转码。
//        Charset gbk = Charset.forName("GBK");
//        ZipFile zip = new  ZipFile(zipFile, gbk);
ZipFile zip = new  ZipFile(zipFile);

for(Enumeration entries = zip.entries();entries.hasMoreElements();){

ZipEntry entry = (ZipEntry)entries.nextElement();
String zipEntryNamePath = entry.getName();
//去掉文件夹的名称
String zipEntryName=zipEntryNamePath.substring(zipEntryNamePath.indexOf("/")+1,zipEntryNamePath.length());
InputStream in = zip.getInputStream(entry);
String outPath = (descDir+zipEntryName).replaceAll("\\*", "/");

//判断路径是否存在,不存在则创建文件路径
File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if(!file.exists()){
file.mkdirs();
}
//判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
if(new File(outPath).isDirectory()){
continue;
}
//输出文件路径信息
System.out.println(outPath);

OutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[1024];
int len;
while((len=in.read(buf1))>0){
out.write(buf1,0,len);
}
in.close();
out.close();
}
System.out.println("******************解压完毕********************");
}
}
注意:经过这样的解压之后,原解压文件是删不掉的,Java虚拟机和压缩文件还有关系,要zipfile关掉才可以删掉,zipfile有个close方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: