導航:首頁 > 文件處理 > java解壓zip

java解壓zip

發布時間:2022-01-12 04:05:13

1. 如何在java解壓zip和rar文件

java中有zip包,可以使用

public void getZipFiles(String zipFile, String destFolder) throws IOException {
BufferedOutputStream dest = null;
ZipInputStream zis = new ZipInputStream(
new BufferedInputStream(
new FileInputStream(zipFile)));
ZipEntry entry;
while (( entry = zis.getNextEntry() ) != null) {
System.out.println( "Extracting: " + entry.getName() );
int count;
byte data[] = new byte[BUFFER];

if (entry.isDirectory()) {
new File( destFolder + "/" + entry.getName() ).mkdirs();
continue;
} else {
int di = entry.getName().lastIndexOf( '/' );
if (di != -1) {
new File( destFolder + "/" + entry.getName()
.substring( 0, di ) ).mkdirs();
}
}
FileOutputStream fos = new FileOutputStream( destFolder + "/"
+ entry.getName() );
dest = new BufferedOutputStream( fos );
while (( count = zis.read( data ) ) != -1)
dest.write( data, 0, count );
dest.flush();
dest.close();
}
}

rar的只能用第三方api,比如junrar

2. 如何使用java壓縮文件夾成為zip包(最簡單的

import java.io.File;

public class ZipCompressorByAnt {

private File zipFile;

/**
* 壓縮文件構造函數
* @param pathName 最終壓縮生成的壓縮文件:目錄+壓縮文件名.zip
*/
public ZipCompressorByAnt(String finalFile) {
zipFile = new File(finalFile);
}

/**
* 執行壓縮操作
* @param srcPathName 需要被壓縮的文件/文件夾
*/
public void compressExe(String srcPathName) {
System.out.println("srcPathName="+srcPathName);

File srcdir = new File(srcPathName);
if (!srcdir.exists()){
throw new RuntimeException(srcPathName + "不存在!");
}

Project prj = new Project();
Zip zip = new Zip();
zip.setProject(prj);
zip.setDestFile(zipFile);
FileSet fileSet = new FileSet();
fileSet.setProject(prj);
fileSet.setDir(srcdir);
//fileSet.setIncludes("**/*.java"); //包括哪些文件或文件夾 eg:zip.setIncludes("*.java");
//fileSet.setExcludes(...); //排除哪些文件或文件夾
zip.addFileset(fileSet);
zip.execute();
}

}

public class TestZip {

public static void main(String[] args) {

ZipCompressorByAnt zca = new ZipCompressorByAnt("E:\test1.zip ");
zca.compressExe("E:\test1");
}

}

/*如果 出現ant 的 52 51 50 等版本問題 可以去找對應的ant-1.8.2.jar 我開始用的ant-1.10.1.jar 就是這個包版本高了 一直報verson 52 版本問題*/

3. java中怎麼用cmd命令解壓zip文件

對於zip文件,java有自帶類庫java.util.zip;可是要想解壓rar文件只能靠第三方類庫,我試過兩個:com.github.junrar和de.innosystec.unrar,前者解壓時可能會出現crcError,後者pom配置時報錯;利用cmd命令調用winRAR進行解壓,無疑方便快捷很多。

調用cmd命令

public static boolean exe(String cmd) {
Runtime runtime = Runtime.getRuntime(); try {
Process p = runtime.exec(cmd);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream(),"GBK"));

String line = reader.readLine(); while(line!=null) {
logger.info(line);
line = reader.readLine();
}
reader.close(); if(p.waitFor()!=0) { return false;
}
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) { // TODO Auto-generated catch block
e.printStackTrace();
} return true;
}

首先利用runtime.exec()執行指令,得到process,從process.getInputStream()中獲取回顯字元並列印,列印回顯時可能會出現中文亂碼,這個和操作系統編碼有關,我這里是GBK編碼,所以在new inputstreamReader時加入了編碼參數」GBK「

命令行字元串

如果需要調用cmd命令,如cd等,可寫」cmd c cd 目錄」。對於直接調用exe執行,則可以寫成」exe文件絕對路徑 參數」,在命令行字元串中,含有空格的路徑或者字元串應該再加上引號,即」」exe文件絕對路徑」 」參數」「

winRAR調用

我這里安裝目錄是C:/Program Files/WinRAR,將D:1.rar 解壓到D:,則寫成」」C:/Program Files/WinRAR/unRar.exe」 x -y D:/1.rar D:/」,x代表絕對路徑解壓,-y表示全部確定;壓縮的命令如下:「」C:/Program Files/WinRAR/rar.exe」 a -ep1 D:2.rar D:源目錄」,a表示添加文件到壓縮文件,-ep1表示排除基本目錄,如D:winrar ar這個目錄,如果沒有-ep1那麼壓縮包中會出現winrar目錄路徑,而加了之後就只將當前目錄打包,只有rar目錄

4. java 解壓zip中文文件保存

用jdk自帶的zip工具做壓縮時,對中文支持不是很好。
建議使用ant.jar中的壓縮和解壓縮工具

5. java 解壓文件

給你找了一個 你參考一下吧:
package com.da.unzip;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class Unzip {

public static void main(String[] args) throws Exception {

Unzip unzip = new Unzip();
String zippath = "C:\\unzip\\";// /解壓到的目標文件路徑
String zipDir = "C:\\data\\";// 要解壓的壓縮文件的存放路徑

File file = new File(zipDir);
List list = unzip.getSubFiles(file);
for (Object obj : list) {
String realname = ((File)obj).getName();
System.out.println(realname);
int end = realname.lastIndexOf(".");
System.out.println("要解壓縮的文件名.........."+zipDir+realname);
System.out.println("解壓到的目錄" +zippath+realname.substring(0, end));
unzip.testReadZip(zippath,zipDir+realname);
}

}

/*
* 解壓縮功能. 將zippath目錄文件解壓到unzipPath目錄下. @throws Exception
*/
public void ReadZip(String zippath, String unzipPath) throws Exception {

ZipFile zfile = new ZipFile(unzipPath);// 生成一個zip文件對象

System.out.println(zfile.getName());// 獲取要解壓的zip的文件名全路徑

Enumeration zList = zfile.entries();// 返回枚舉對象

ZipEntry ze = null;// 用於表示 ZIP 文件條目

byte[] buf = new byte[1024];// 聲明位元組數組
/**
* 循環獲取zip文件中的每一個文件
*/
while (zList.hasMoreElements()) {
// 從ZipFile中得到一個ZipEntry
ze = (ZipEntry) zList.nextElement();
if (ze.isDirectory())// 如果為目錄條目,則返回 true,執行下列語句
{
System.out.println("Dir: " + ze.getName() + " skipped..");
continue;
}
int begin = zfile.getName().lastIndexOf("\\") + 1;
int end = zfile.getName().lastIndexOf(".");
String zipRealName = zfile.getName().substring(begin, end);
System.out.println("解壓縮開始Extracting:"+ze.getName()+"\t"+ze.getSize()+"\t"+ze.getCompressedSize());
// 以ZipEntry為參數得到一個InputStream,並寫到OutputStream中,並加上緩沖
OutputStream os = new BufferedOutputStream(
new FileOutputStream(getRealFileName(zippath + "\\"
+ zipRealName, ze.getName())));
InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
String fileName = getRealFileName(zippath, ze.getName()).getName();
System.out.println("解壓出的文件名稱:" + fileName);
int readLen = 0;
while ((readLen = is.read(buf, 0, 1024)) != -1) {
os.write(buf, 0, readLen);
}
is.close();
os.close();
// System.out.println("解壓縮結束Extracted: "+ze.getName());
}
zfile.close();
}

/**
* 給定根目錄,返回一個相對路徑所對應的實際文件名.
*
* @param zippath
* 指定根目錄
* @param absFileName
* 相對路徑名,來自於ZipEntry中的name
* @return java.io.File 實際的文件
*/
private File getRealFileName(String zippath, String absFileName) {

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

File ret = new File(zippath);// 創建文件對象

if (dirs.length > 1) {
for (int i = 0; i < dirs.length - 1; i++) {
ret = new File(ret, dirs[i]);

}
}

if (!ret.exists()) {// 檢測文件是否存在
ret.mkdirs();// 創建此抽象路徑名指定的目錄
}
ret = new File(ret, dirs[dirs.length - 1]);// 根據 ret 抽象路徑名和 child
// 路徑名字元串創建一個新 File 實例

return ret;
}

}

6. java如何解壓頁面上傳到伺服器的zip文件

這個轉換肯定是會出錯的,struts 的formFile跟zipFile沒有直接關系,怎麼能這么強制轉化呢?
建議
1. 把文件保存到一個臨時目錄(保存為zip文件)
2. 讀取這個文件
3. 抽取想要的文件
4. 把臨時文件刪除

7. java如何解壓一個ZIP壓縮過的數據

1樓的方法。先解壓開後,你再把文件讀成流,把數據存資料庫

8. 怎樣用java快速實現zip文件的壓縮解壓縮

packagezip;
importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.util.Enumeration;
importjava.util.zip.CRC32;
importjava.util.zip.CheckedOutputStream;
importjava.util.zip.ZipEntry;
importjava.util.zip.ZipFile;
importjava.util.zip.ZipOutputStream;
importorg.apache.commons.lang3.StringUtils;
publicclassZipUtil{

/**
*遞歸壓縮文件夾
*@paramsrcRootDir壓縮文件夾根目錄的子路徑
*@paramfile當前遞歸壓縮的文件或目錄對象
*@paramzos壓縮文件存儲對象
*@throwsException
*/
privatestaticvoidzip(StringsrcRootDir,Filefile,ZipOutputStreamzos)throwsException
{
if(file==null)
{
return;
}

//如果是文件,則直接壓縮該文件
if(file.isFile())
{
intcount,bufferLen=1024;
bytedata[]=newbyte[bufferLen];

//獲取文件相對於壓縮文件夾根目錄的子路徑
StringsubPath=file.getAbsolutePath();
intindex=subPath.indexOf(srcRootDir);
if(index!=-1)
{
subPath=subPath.substring(srcRootDir.length()+File.separator.length());
}
ZipEntryentry=newZipEntry(subPath);
zos.putNextEntry(entry);
BufferedInputStreambis=newBufferedInputStream(newFileInputStream(file));
while((count=bis.read(data,0,bufferLen))!=-1)
{
zos.write(data,0,count);
}
bis.close();
zos.closeEntry();
}
//如果是目錄,則壓縮整個目錄
else
{
//壓縮目錄中的文件或子目錄
File[]childFileList=file.listFiles();
for(intn=0;n<childFileList.length;n++)
{
childFileList[n].getAbsolutePath().indexOf(file.getAbsolutePath());
zip(srcRootDir,childFileList[n],zos);
}
}
}

/**
*對文件或文件目錄進行壓縮
*@paramsrcPath要壓縮的源文件路徑。如果壓縮一個文件,則為該文件的全路徑;如果壓縮一個目錄,則為該目錄的頂層目錄路徑
*@paramzipPath壓縮文件保存的路徑。注意:zipPath不能是srcPath路徑下的子文件夾
*@paramzipFileName壓縮文件名
*@throwsException
*/
publicstaticvoidzip(StringsrcPath,StringzipPath,StringzipFileName)throwsException
{
if(StringUtils.isEmpty(srcPath)||StringUtils.isEmpty(zipPath)||StringUtils.isEmpty(zipFileName))
{
thrownewParameterException(ICommonResultCode.PARAMETER_IS_NULL);
}
CheckedOutputStreamcos=null;
ZipOutputStreamzos=null;
try
{
FilesrcFile=newFile(srcPath);

//判斷壓縮文件保存的路徑是否為源文件路徑的子文件夾,如果是,則拋出異常(防止無限遞歸壓縮的發生)
if(srcFile.isDirectory()&&zipPath.indexOf(srcPath)!=-1)
{
thrownewParameterException(ICommonResultCode.INVALID_PARAMETER,".");
}

//判斷壓縮文件保存的路徑是否存在,如果不存在,則創建目錄
FilezipDir=newFile(zipPath);
if(!zipDir.exists()||!zipDir.isDirectory())
{
zipDir.mkdirs();
}

//創建壓縮文件保存的文件對象
StringzipFilePath=zipPath+File.separator+zipFileName;
FilezipFile=newFile(zipFilePath);
if(zipFile.exists())
{
//檢測文件是否允許刪除,如果不允許刪除,將會拋出SecurityException
=newSecurityManager();
securityManager.checkDelete(zipFilePath);
//刪除已存在的目標文件
zipFile.delete();
}

cos=newCheckedOutputStream(newFileOutputStream(zipFile),newCRC32());
zos=newZipOutputStream(cos);

//如果只是壓縮一個文件,則需要截取該文件的父目錄
StringsrcRootDir=srcPath;
if(srcFile.isFile())
{
intindex=srcPath.lastIndexOf(File.separator);
if(index!=-1)
{
srcRootDir=srcPath.substring(0,index);
}
}
//調用遞歸壓縮方法進行目錄或文件壓縮
zip(srcRootDir,srcFile,zos);
zos.flush();
}
catch(Exceptione)
{
throwe;
}
finally
{
try
{
if(zos!=null)
{
zos.close();
}
}
catch(Exceptione)
{
e.printStackTrace();
}
}
}

/**
*解壓縮zip包
*@paramzipFilePathzip文件的全路徑
*@paramunzipFilePath解壓後的文件保存的路徑
*@paramincludeZipFileName解壓後的文件保存的路徑是否包含壓縮文件的文件名。true-包含;false-不包含
*/
@SuppressWarnings("unchecked")
publicstaticvoinzip(StringzipFilePath,StringunzipFilePath,booleanincludeZipFileName)throwsException
{
if(StringUtils.isEmpty(zipFilePath)||StringUtils.isEmpty(unzipFilePath))
{
thrownewParameterException(ICommonResultCode.PARAMETER_IS_NULL);
}
FilezipFile=newFile(zipFilePath);
//如果解壓後的文件保存路徑包含壓縮文件的文件名,則追加該文件名到解壓路徑
if(includeZipFileName)
{
StringfileName=zipFile.getName();
if(StringUtils.isNotEmpty(fileName))
{
fileName=fileName.substring(0,fileName.lastIndexOf("."));
}
unzipFilePath=unzipFilePath+File.separator+fileName;
}
//創建解壓縮文件保存的路徑
FileunzipFileDir=newFile(unzipFilePath);
if(!unzipFileDir.exists()||!unzipFileDir.isDirectory())
{
unzipFileDir.mkdirs();
}

//開始解壓
ZipEntryentry=null;
StringentryFilePath=null,entryDirPath=null;
FileentryFile=null,entryDir=null;
intindex=0,count=0,bufferSize=1024;
byte[]buffer=newbyte[bufferSize];
BufferedInputStreambis=null;
BufferedOutputStreambos=null;
ZipFilezip=newZipFile(zipFile);
Enumeration<ZipEntry>entries=(Enumeration<ZipEntry>)zip.entries();
//循環對壓縮包里的每一個文件進行解壓
while(entries.hasMoreElements())
{
entry=entries.nextElement();
//構建壓縮包中一個文件解壓後保存的文件全路徑
entryFilePath=unzipFilePath+File.separator+entry.getName();
//構建解壓後保存的文件夾路徑
index=entryFilePath.lastIndexOf(File.separator);
if(index!=-1)
{
entryDirPath=entryFilePath.substring(0,index);
}
else
{
entryDirPath="";
}
entryDir=newFile(entryDirPath);
//如果文件夾路徑不存在,則創建文件夾
if(!entryDir.exists()||!entryDir.isDirectory())
{
entryDir.mkdirs();
}

//創建解壓文件
entryFile=newFile(entryFilePath);
if(entryFile.exists())
{
//檢測文件是否允許刪除,如果不允許刪除,將會拋出SecurityException
=newSecurityManager();
securityManager.checkDelete(entryFilePath);
//刪除已存在的目標文件
entryFile.delete();
}

//寫入文件
bos=newBufferedOutputStream(newFileOutputStream(entryFile));
bis=newBufferedInputStream(zip.getInputStream(entry));
while((count=bis.read(buffer,0,bufferSize))!=-1)
{
bos.write(buffer,0,count);
}
bos.flush();
bos.close();
}
}

publicstaticvoidmain(String[]args)
{
StringzipPath="d:\ziptest\zipPath";
Stringdir="d:\ziptest\rawfiles";
StringzipFileName="test.zip";
try
{
zip(dir,zipPath,zipFileName);
}
catch(Exceptione)
{
e.printStackTrace();
}

StringzipFilePath="D:\ziptest\zipPath\test.zip";
StringunzipFilePath="D:\ziptest\zipPath";
try
{
unzip(zipFilePath,unzipFilePath,true);
}
catch(Exceptione)
{
e.printStackTrace();
}
}
}

9. java 解壓zip 密碼

調用開源項目winzipaes。

AesZipFileDecrypter zipFile = new AesZipFileDecrypter( new File("doc/zipSpecificationAes.zip") );
ExtZipEntry entry = zipFile.getEntry( "zipSpecification.txt" );
zipFile.extractEntry( entry, new File("doc/zipSpecification.txt"), "foo" );

具體參考下面鏈接

10. java zip解壓

如果把out.close()寫在注釋處,那麼意味著while循環中創建的out輸出流對象沒有關閉,要知道,如果這個流沒有關閉,那麼該流緩沖區中的數據不會被刷新到實際目標文件中。
因此只有最後一個文件有內容(因為out被關閉時指向最後一個文件)。

閱讀全文

與java解壓zip相關的資料

熱點內容
聯想小新電腦怎麼解壓文件在哪裡 瀏覽:225
while語句java 瀏覽:358
銀行加密貨幣儲蓄 瀏覽:461
map默認參數python 瀏覽:423
山西性能優良壓縮機 瀏覽:197
歐洲tcc編程式模式公司 瀏覽:984
app的股權與投資怎麼寫 瀏覽:580
php網站首頁文件 瀏覽:585
工商銀行app怎麼支持兩個手機登錄 瀏覽:106
安卓手機如何搭建ssr伺服器 瀏覽:668
文件解壓到一半跳出來需要密碼 瀏覽:892
phpmysql編譯pdo 瀏覽:514
怎麼查看公司郵箱伺服器地址 瀏覽:571
php可忽略大小寫的模式符 瀏覽:947
白熊app稿費怎麼樣 瀏覽:464
新建的命令為 瀏覽:426
數組兩種查找演算法集合 瀏覽:757
dw怎麼將源碼拆成幾個文件 瀏覽:231
驗演算法復核法 瀏覽:997
電腦管機就刪除文件夾 瀏覽:482