最近要写段代码在windows下解压文件,开始解压rar不成功,程序没报错,用debug也看不出问题。最后在网上查询出rar解压算法收费,zip是免费的。顺便把代码贴出来。
package com.comtop.top.emc.test;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
import java.util.zip.ZipInputStream;
/**
* 解压文件以及删除
*
*/
public class ZipFile {
public static void main(String[] args) {
try {
readByZipInputStream("D:\\gg\\gg.zip","D:\\");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param archive 压缩包路径
* @param decompressDir 解压文件夹路径
*/
public static void readByZipInputStream(String archive, String decompressDir){
System.out.println("开始读压缩文件");
BufferedInputStream objBufferInputStream = null;
BufferedOutputStream objBufferedOutputStream = null;
ZipInputStream in2 = null;
CheckedInputStream csumi = null;
try{
FileInputStream fi = new FileInputStream(archive);
csumi = new CheckedInputStream(fi, new CRC32());
in2 = new ZipInputStream(csumi);
objBufferInputStream = new BufferedInputStream(in2);
java.util.zip.ZipEntry ze;//压缩文件条目
//遍历压缩包中的文件条目
while ((ze = in2.getNextEntry()) != null) {
String entryName = ze.getName();
if (ze.isDirectory()) {
System.out.println("正在创建解压目录 - " + entryName);
File decompressDirFile = new File(decompressDir + "/" + entryName);
if (!decompressDirFile.exists()) {
decompressDirFile.mkdirs();
}
} else {
System.out.println("正在创建解压文件 - " + entryName);
objBufferedOutputStream = new BufferedOutputStream(new FileOutputStream(
decompressDir + "/" + entryName));
byte[] buffer = new byte[1024];
int readCount = objBufferInputStream.read(buffer);
while (readCount != -1) {
objBufferedOutputStream.write(buffer, 0, readCount);
readCount = objBufferInputStream.read(buffer);
}
}
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
if(objBufferedOutputStream != null){
try{
objBufferedOutputStream.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
if(objBufferInputStream != null){
try{
objBufferInputStream.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
System.out.println("-------------------解压成功!");
}
}