解压zip文件
没什么太大的问题
/**
* 解压缩zip文件
*
* @param fileName
* 要解压的文件名 包含路径 如:"c:\\test.zip"
* @param filePath
* 解压后存放文件的路径 如:"c:\\temp\\"
* @throws Exception
*/
@SuppressWarnings("rawtypes")
public static void unZip(String fileName, String filePath) throws Exception {
if(!filePath.endsWith(File.separator)){
filePath += File.separator;
}
int lastBackslashIndex=fileName.lastIndexOf('\\');
int lastCommaIndex=fileName.lastIndexOf('.');
String folderName=fileName.substring(lastBackslashIndex+1,lastCommaIndex);
filePath=filePath+folderName+File.separator;
ZipFile zipFile = new ZipFile(fileName, "GBK"); // 以“GBK”编码创建zip文件,用来处理winRAR压缩的文件。
Enumeration emu = zipFile.getEntries();
while (emu.hasMoreElements()) {
ZipEntry entry = (ZipEntry) emu.nextElement();
if (entry.isDirectory()) {
new File(filePath + entry.getName()).mkdirs();
continue;
}
BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
File file = new File(filePath + entry.getName());
File parent = file.getParentFile();
if (parent != null && (!parent.exists())) {
parent.mkdirs();
}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER);
byte[] buf = new byte[BUFFER];
int len = 0;
while ((len = bis.read(buf, 0, BUFFER)) != -1) {
fos.write(buf, 0, len);
}
bos.flush();
bos.close();
bis.close();
System.out.println("解压文件:" + file.getName());
}
System.out.println("unzip done");
zipFile.close();
}
解压rar文件
1.前提: rar4文件
解压时,格式设置为rar4
/**
* @param rarFileName rar file name
* @param outFilePath output file path
* @throws Exception
*/
public static void unrar(String rarFileName, String outFilePath) throws Exception{
rarFileName = rarFileName.replaceAll("\\\\", "/");
int lastBackslashIndex=rarFileName.lastIndexOf('/');
int lastCommaIndex=rarFileName.lastIndexOf('.');
String folderName=rarFileName.substring(lastBackslashIndex+1,lastCommaIndex);
//outFilePath = outFilePath+File.separator+rarFileName.substring(rarFileName.lastIndexOf("/"),rarFileName.lastIndexOf("."));
Archive archive = new Archive(new File(rarFileName));
List<FileHeader> files = archive.getFileHeaders();
for (FileHeader fh : files) {
String fileName = fh.getFileNameString();
if(fileName != null && fileName.trim().length() > 0 && fh.getFileAttr() == 32){
String saveFileName = outFilePath+"\\"+ folderName+"\\"+fileName;
File saveFile = new File(saveFileName);
File parent = saveFile.getParentFile();
if(!parent.exists()){
parent.mkdirs();
}
if(!saveFile.exists()){
saveFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(saveFile);
archive.extractFile(fh, fos);
fos.flush();
fos.close();
}
}
archive.close();
}