解壓和壓縮文件

1.解壓文件

1.1解壓zip文件,用到的是apache.tools.zip下的包

代碼如下:

/**

* @param sourceFileName
*            要解壓縮的zip文件
* @param desDir
*            解壓縮到的目錄
* @throws IOException
*/
public static String unZip(String sourceFileName, String desDir)
throws IOException {
// 創建壓縮文件對象
ZipFile zf = new ZipFile(new File(sourceFileName));
// 獲取壓縮文件中的文件枚舉
Enumeration<ZipEntry> en = zf.getEntries();
int length = 0;
byte[] b = new byte[1024];
// 提取壓縮文件夾中的所有壓縮實例對象
while (en.hasMoreElements()) {
ZipEntry ze = en.nextElement();
// 創建解壓縮後的文件實例對象
File f = new File(desDir + File.separator + ze.getName());
// 如果當前壓縮文件中的實例對象是文件夾,就在解壓縮後的文件夾中創建該文件
if (ze.isDirectory()) {
f.mkdirs();
} else {
// 如果當前解壓縮文件的父級文件沒有創建的話,則創建父級文件夾
if (!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
// 將當前文件的內容寫入解壓後的文件夾中
// f = new File(desDir + File.separator + DateUtil.nowDate().getTime() + ze.getName());
String newName = ze.getName().substring(0, ze.getName().lastIndexOf("."));
newName = new
Name + DateUtil.nowDate().getTime();
newName = newName + ze.getName().substring(ze.getName().lastIndexOf("."));
f = new File(desDir + File.separator + newName);
OutputStream outputStream = new FileOutputStream(f);
InputStream inputStream = zf.getInputStream(ze);
while ((length = inputStream.read(b)) > 0) {
outputStream.write(b, 0, length);
}


inputStream.close();
outputStream.close();
}
}
zf.close();
new File(sourceFileName).delete();
System.out.println("******************解壓完畢********************");
return desDir;
}

1.2解壓rar文件

代碼如下:

/**
* 解壓rar格式壓縮包。
* 對應的是java-unrar-0.3.jar,但是java-unrar-0.3.jar又會用到commons-logging-1.1.1.jar
*/
public static String unrar(String sourceRar, String destDir)
throws Exception {
Archive a = null;
FileOutputStream fos = null;
a = new Archive(new File(sourceRar));
FileHeader fh = a.nextFileHeader();
while (fh != null) {
if (!fh.isDirectory()) {
// 1 根據不同的操作系統拿到相應的 destDirName 和 destFileName
// String compressFileName = fh.getFileNameString().trim();
String compressFileName = fh.getFileNameW().trim();
if ("".equals(compressFileName)) {
compressFileName = fh.getFileNameString().trim();
}
String destFileName = "";
String destDirName = "";
String newName = "";
// 非windows系統
if (File.separator.equals("/")) {
destFileName = destDir + File.separator
+ compressFileName.replaceAll("\\\\", "/");
//防止上傳到ftp時重名,導致文件被覆蓋
newName = destFileName.substring(0, destFileName.lastIndexOf(".")) + DateUtil.nowDate().getTime();
newName = newName + destFileName.substring(destFileName.lastIndexOf("."));
destDirName = newName.substring(0,
destFileName.lastIndexOf("/"));
// windows系統
} else {
destFileName = destDir + File.separator
+ compressFileName.replaceAll("/", "\\\\");
//防止上傳到ftp時重名,導致文件被覆蓋
newName = destFileName.substring(0, destFileName.lastIndexOf(".")) + DateUtil.nowDate().getTime();
newName = newName + destFileName.substring(destFileName.lastIndexOf("."));
destDirName = newName.substring(0,
destFileName.lastIndexOf("\\"));
}
// 2創建文件夾
File dir = new File(destDirName);
if (!dir.exists() || !dir.isDirectory()) {
dir.mkdirs();
}
// 3解壓縮文件
fos = new FileOutputStream(new File(newName));
a.extractFile(fh, fos);
fos.close();
fos = null;
}
fh = a.nextFileHeader();
}
a.close();
// a = null;
new File(sourceRar).delete();
return destDir;
}

2.生成zip文件

/**
* 創建臨時文件夾,並生成zip
* @throws Exception 
*/
@Override
public String createAndZip(String[] recordIdArr) throws Exception {
String path = FileUtil.PATH + "RSRC";
File file = new File(path);
if(!file.exists()){
file.mkdir();
}
for(String recordId : recordIdArr){
file = new File(path + File.separator + recordId);
if(!file.exists()){
file.mkdir();
}
// for(Object recordType : RecordType.values()){
// file = new File(path + File.separator + recordId + File.separator + recordType.toString());
// if(!file.exists()){
// file.mkdir();
// }
// }
//查詢檔案類型,並創建對應的多級文件目錄
List<TreeInfo> treeList = treeService.searchAll(); 
TreeInfo treeUtils = TreeInfo.buildTree(treeList);
List<TreeInfo> trees = treeUtils.getChildren();
for(TreeInfo tree : trees){
String filePath = path + File.separator + recordId;
createDir(tree, filePath);
}
}
// FileUtil.zip(path, path+".zip");
File[] files = new File(path).listFiles();
List<File> filesList = new ArrayList<File>();
for(File f : files){
filesList.add(f);
}
FileUtil.toZip(filesList, new File(path + ".zip"), "", 9);
return path + ".zip";
}


public static void toZip(List<File> files,File zipFile,String path,int level)throws Exception{
File zipParnt = zipFile.getParentFile();
if(!zipParnt.exists()){
zipParnt.mkdirs();
}
if(path == null){
path = "";
}else if(path.length() > 0 && !path.endsWith(File.separator)){
path += File.separator;
}
//ZIP輸出流
FileOutputStream fos = null;
ZipOutputStream zos = null;
try{
//創建ZIP輸出流
fos = new FileOutputStream(zipFile);
//解決中文的關鍵所在
zos = new ZipOutputStream(fos);
//設置壓縮級別
zos.setLevel(level < 0 ? 0 : (level > 9 ? 9 : level));
//開始壓縮文件列表
Set<String> entryNames = new HashSet<String>();
int num = 1;
for(File f : files){
if(f.exists()){
//以文件名爲entry名,如重複則前面加數字
String entryName = f.getName();
while(entryNames.contains(entryName)){
entryName = ("("+num+++")") + f.getName();
}
writeEntry(zos,f,path,entryName);
entryNames.add(entryName);
}
}
}finally{
//關閉ZIP輸出流
try {
zos.close();
} catch (Exception e) {}
try {
fos.close();
} catch (Exception e) {}
}
}


private static void writeEntry(ZipOutputStream zos,File f,String path,String entryName)throws Exception{
//如果是目錄
if(f.isDirectory()){
File[] list = f.listFiles();
//如果爲空目錄,也加入壓縮文件
if(list.length == 0){
zos.putNextEntry(new ZipEntry(path + entryName + File.separator));
}else{
path = path + f.getName() + File.separator;
for(File fl : list){
writeEntry(zos, fl,path,fl.getName());
}
}
return;
}
//文件輸入流
FileInputStream fis = null;
BufferedInputStream bis = null;
try{
//創建文件輸入流
fis = new FileInputStream(f);
bis = new BufferedInputStream(fis);
//根據當前待壓縮文件添加壓縮條目
zos.putNextEntry(new ZipEntry(path + entryName));
//寫入條目內容
byte[] buf = new byte[1024];
int len;
while((len = bis.read(buf)) != -1){
zos.write(buf,0,len);
}
}finally{
//關閉文件輸入流
try {
bis.close();
} catch (Exception e) {}
try {
fis.close();
} catch (Exception e) {}
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章