一、对rar文件的解压缩
1、maven
<dependency>
<groupId>com.github.junrar</groupId>
<artifactId>junrar</artifactId>
<version>0.7</version>
</dependency>
2、解压类
import java.io.File;
import java.io.FileOutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;
/**
* rar的解压
*/
public class UnRar {
/**
*
* @param srcRarPath rar文件完整路径
* @param dstDirectoryPath 解压到的文件夹
*/
public static void unrar(String srcRarPath,String dstDirectoryPath){
if (!srcRarPath.toLowerCase().endsWith(".rar")) {
/**
* 抛出异常
*/
System.out.println("非rar文件!");
return;
}
File dstDiretory = new File(dstDirectoryPath);
if (!dstDiretory.exists()) {// 目标目录不存在时,创建该文件夹
dstDiretory.mkdirs();
}
File fol=null,out=null;
Archive a = null;
try {
a = new Archive(new File(srcRarPath));
if (a != null){
//a.getMainHeader().print(); // 打印文件信息.
FileHeader fh = a.nextFileHeader();
while (fh != null){
if (fh.isDirectory()) { // 文件夹
// 如果是中文路径,调用getFileNameW()方法,否则调用getFileNameString()方法,还可以使用if(fh.isUnicode())
if(existZH(fh.getFileNameW())){
fol = new File(dstDirectoryPath + File.separator
+ fh.getFileNameW());
}else{
fol = new File(dstDirectoryPath + File.separator
+ fh.getFileNameString());
}
fol.mkdirs();
} else { // 文件
if(existZH(fh.getFileNameW())){
out = new File(dstDirectoryPath + File.separator
+ fh.getFileNameW().trim());
}else{
out = new File(dstDirectoryPath + File.separator
+ fh.getFileNameString().trim());
}
try {// 之所以这么写try,是因为万一这里面有了异常,不影响继续解压.
if (!out.exists()) {
if (!out.getParentFile().exists()){// 相对路径可能多级,可能需要创建父目录.
out.getParentFile().mkdirs();
}
out.createNewFile();
}
FileOutputStream os = new FileOutputStream(out);
a.extractFile(fh, os);
os.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
fh = a.nextFileHeader();
}
a.close();
}
} catch (Exception e){
e.printStackTrace();
}
}
/**
* 判断是否中文
* @param str
* @return
*/
public static boolean existZH(String str){
String regEx = "[\\u4e00-\\u9fa5]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
while (m.find()) {
return true;
}
return false;
}
}
2、对zip文件的压缩与解压缩
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
/**
* Zip压缩/解压缩工具类
* 实现对目标路径及其子路径下的所有文件及空目录的压缩
* 参考网上若干种实现,并修改其bug
*
* @version v0.1, 17/09/04
* @author Kiwi Liu
*/
public class ZipUtil {
/** 缓冲器大小 */
private static final int BUFFER = 512;
/**
* 取的给定源目录下的所有文件及空的子目录
* 递归实现
*
* @param srcFile
*
* @return
*/
private static List<File> getAllFiles(File srcFile) {
List<File> fileList = new ArrayList<File>();
File[] tmp = srcFile.listFiles();
for (int i = 0; i < tmp.length; i++) {
if (tmp[i].isFile()) {
fileList.add(tmp[i]);
System.out.println("add file: "+tmp[i].getName());
}
if (tmp[i].isDirectory()) {
if (tmp[i].listFiles().length!=0){//若不是空目录,则递归添加其下的目录和文件
fileList.addAll(getAllFiles(tmp[i]));
}
else{//若是空目录,则添加这个目录到fileList
fileList.add(tmp[i]);
System.out.println("add empty dir: "+tmp[i].getName());
}
}
} // end for
return fileList;
}
/**
* 取相对路径
* 依据文件名和压缩源路径得到文件在压缩源路径下的相对路径
*
* @param dirPath 压缩源路径
* @param file
*
* @return 相对路径
*/
private static String getRelativePath(String dirPath, File file) {
File dir = new File(dirPath);
String relativePath = file.getName();
while (true) {
file = file.getParentFile();
if (file == null) {
break;
}
if (file.equals(dir)) {
break;
} else {
relativePath = file.getName() + "/" + relativePath;
}
} // end while
return relativePath;
}
/**
* 创建文件
* 根据压缩包内文件名和解压缩目的路径,创建解压缩目标文件,
* 生成中间目录
* @param dstPath 解压缩目的路径
* @param fileName 压缩包内文件名
*
* @return 解压缩目标文件
*
* @throws IOException
*/
private static File createFile(String dstPath, String fileName) throws IOException {
String[] dirs = fileName.split("/");//将文件名的各级目录分解
File file = new File(dstPath);
if (dirs.length > 1) {//文件有上级目录
for (int i = 0; i < dirs.length - 1; i++) {
file = new File(file, dirs[i]);//依次创建文件对象知道文件的上一级目录
}
if (!file.exists()) {
file.mkdirs();//文件对应目录若不存在,则创建
System.out.println("mkdirs: " + file.getCanonicalPath());
}
file = new File(file, dirs[dirs.length - 1]);//创建文件
return file;
} else {
if (!file.exists()) {
file.mkdirs();//若目标路径的目录不存在,则创建
System.out.println("mkdirs: " + file.getCanonicalPath());
}
file = new File(file, dirs[0]);//创建文件
return file;
}
}
/**
* 解压缩方法
*
*
* @param zipFileName 压缩文件名
* @param dstPath 解压目标路径
*
* @return
*/
public static boolean unzip(String zipFileName, String dstPath) {
System.out.println("zip uncompressing...");
try {
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFileName));
ZipEntry zipEntry = null;
byte[] buffer = new byte[BUFFER];//缓冲器
int readLength = 0;//每次读出来的长度
//System.out.println(zipInputStream.getNextEntry().getName());
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
if (zipEntry.isDirectory()) {//若是zip条目目录,则需创建这个目录
File dir = new File(dstPath + "/" + zipEntry.getName());
if (!dir.exists()) {
dir.mkdirs();
System.out.println("mkdirs: " + dir.getCanonicalPath());
continue;//跳出
}
}
File file = createFile(dstPath, zipEntry.getName());//若是文件,则需创建该文件
System.out.println("file created: " + file.getCanonicalPath());
OutputStream outputStream = new FileOutputStream(file);
while ((readLength = zipInputStream.read(buffer, 0, BUFFER)) != -1) {
outputStream.write(buffer, 0, readLength);
}
outputStream.close();
System.out.println("file uncompressed: " + file.getCanonicalPath());
} // end while
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
e.printStackTrace();
System.out.println("unzip fail!");
return false;
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
System.out.println("unzip fail!");
return false;
}
System.out.println("unzip success!");
return true;
}
/**
* 压缩方法
* (可以压缩空的子目录)
* @param srcPath 压缩源路径
* @param zipFileName 目标压缩文件
*
* @return
*/
public static boolean zip(String srcPath, String zipFileName) {
System.out.println("zip compressing...");
File srcFile = new File(srcPath);
List<File> fileList = getAllFiles(srcFile);//所有要压缩的文件
byte[] buffer = new byte[BUFFER];//缓冲器
ZipEntry zipEntry = null;
int readLength = 0;//每次读出来的长度
try {
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileName));
for (File file : fileList) {
if (file.isFile()){//若是文件,则压缩这个文件
System.out.println("file==============="+getRelativePath(srcPath, file));
zipEntry = new ZipEntry(getRelativePath(srcPath, file));
zipEntry.setSize(file.length());
zipEntry.setTime(file.lastModified());
zipOutputStream.putNextEntry(zipEntry);
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
while ((readLength = inputStream.read(buffer, 0, BUFFER)) != -1) {
zipOutputStream.write(buffer, 0, readLength);
}
inputStream.close();
// System.out.println("file compressed: " + file.getCanonicalPath());
}else {//若是目录(即空目录)则将这个目录写入zip条目
System.out.println("dic==============="+getRelativePath(srcPath, file));
zipEntry = new ZipEntry(getRelativePath(srcPath, file)+"/");
zipOutputStream.putNextEntry(zipEntry);
// System.out.println("dir compressed: " + file.getCanonicalPath()+"/");
}
} // end for
zipOutputStream.close();
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
e.printStackTrace();
System.out.println("zip fail!");
return false;
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
System.out.println("zip fail!");
return false;
}
System.out.println("zip success!");
return true;
}
/**
*
* @param fileList 需要压缩的文件list
* @param zipFileName 压缩文件的路径加名字
* @return
*/
public static boolean zip2(List<File> fileList,String zipFileName) {
System.out.println("zip compressing...");
byte[] buffer = new byte[BUFFER];//缓冲器
ZipEntry zipEntry = null;
int readLength = 0;//每次读出来的长度
try {
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileName));
for (File file : fileList) {
if (file.isFile()){//若是文件,则压缩这个文件
zipEntry = new ZipEntry(file.getName());
zipEntry.setSize(file.length());
zipEntry.setTime(file.lastModified());
zipOutputStream.putNextEntry(zipEntry);
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
while ((readLength = inputStream.read(buffer, 0, BUFFER)) != -1) {
zipOutputStream.write(buffer, 0, readLength);
}
inputStream.close();
System.out.println("file compressed: " + file.getCanonicalPath());
}else {//若是目录(即空目录)则将这个目录写入zip条目
zipEntry = new ZipEntry(file.getName()+"/");
zipOutputStream.putNextEntry(zipEntry);
System.out.println("dir compressed: " + file.getCanonicalPath()+"/");
}
} // end for
zipOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
System.out.println("zip success!");
return true;
}
}