java 文件解压

来源:互联网 发布:申报教学软件 编辑:程序博客网 时间:2024/04/30 16:32
 

可以解决包含中文文件夹的zip包解压的问题

/**

* 解压缩zipFile

* @param file 要解压的zip文件对象

* @param outputDir 要解压到某个指定的目录下

* @throws IOException

*/

public void unzip(String zipFileName, String outputDir) throws IOException {

try {

BufferedOutputStream bos = null;

// 创建输入字节流

FileInputStream fis = new FileInputStream(zipFileName);

// 根据输入字节流创建输入字符流

BufferedInputStream bis = new BufferedInputStream(fis);

// 根据字符流,创建ZIP文件输入流

ZipInputStream zis = new ZipInputStream(bis);

// zip文件条目,表示zip文件

ZipEntry entry;

// 循环读取文件条目,只要不为空,就进行处理

while ((entry = zis.getNextEntry()) != null) {

int count;

byte date[] = new byte[2048];

// 如果条目是文件目录,则继续执行

if (entry.isDirectory()) {

continue;

} else {

int begin = zipFileName.lastIndexOf("\\") + 1;

int end = zipFileName.lastIndexOf(".") + 1;

String zipRealName = zipFileName.substring(begin, end);

bos = new BufferedOutputStream(new FileOutputStream(this

.getRealFileName(outputDir + "\\" + zipRealName,

entry.getName())));

while ((count = zis.read(date)) != -1) {

bos.write(date, 0, count);

}

bos.flush();

bos.close();

}

}

zis.close();

} catch (Exception e) {

e.printStackTrace();

}

}

private File getRealFileName(String zippath, String absFileName) {

String[] dirs = absFileName.split("/", absFileName.length());

// 创建文件对象

File file = new File(zippath);

if (dirs.length > 1) {

for (int i = 0; i < dirs.length - 1; i++) {

// 根据file抽象路径和dir路径字符串创建一个新的file对象,路径为文件的上一个目录

file = new File(file, dirs[i]);

}

}

if (!file.exists()) {

file.mkdirs();

}

file = new File(file, dirs[dirs.length - 1]);

return file;

}

原创粉丝点击