導航:首頁 > 文件教程 > java解析壓縮文件

java解析壓縮文件

發布時間:2022-09-11 09:19:56

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

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

❷ java如何解壓.gz後綴的壓縮包

  1. File file = new File(zipFilePath); 將zip文件路徑轉換 成文件

  2. zipFile = new ZipFile(file); 調用java util下面的zipfile類

  3. Enumeration<?> zipEnum = zipFile.entries(); 將zip文件裡面的內容都放在迭代器裡面了

  4. ZipEntry entry = (ZipEntry) zipEnum.nextElement();,然後迭代出ZipEntry對象。

  5. zipFile.getInputStream(entry)就可以得到所需要的流了,之後做你需要的操作。

❸ java如何直接解壓zip格式二進制流

Java代碼
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

class ZipTest {
// 壓縮
public static void zip(String zipFileName, String inputFile)
throws Exception {
File f = new File(inputFile);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
zipFileName));
zip(out, f, f.getName());
System.out.println("zip done");
out.close();

❹ java解壓zip文件

import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;

/**
* 獲得zip文件里的所有文件
* @author Administrator
*
*/
public class ZipFile {

public ZipFile() throws IOException
{
java.util.zip.ZipFile zf = new java.util.zip.ZipFile("E:/Java/Project.zip");
Enumeration e = zf.entries();
while(e.hasMoreElements())
{
ZipEntry ze = (ZipEntry) e.nextElement();
if(!ze.isDirectory())
System.out.println(new String(ze.getName().getBytes("ISO-8859-1"), "GB2312"));
}
}
public static void main(String[] args) {
try {
new ZipFile();
} catch (IOException e) {
e.printStackTrace();
}
}

}

❺ Java壓縮與解壓縮問題

/**
*類名:zipFileRelease
*說明:一個zip文件解壓類
*介紹:主要的zip文件釋放方法releaseHandle()
* 用ZipInputStream類和ZipEntry類將zip文件的入口清單列舉出來,然後
* 根據用戶提供的輸出路徑和zip文件的入口進行組合通過DataOutputStream
* 和File類進行文件的創建和目錄的創建,創建文件時的文件數據是通過
* ZipInputStream類、ZipEntry類、InputStream類之間的套嵌組合獲得的。
*注意:如果zip文件中包含中文路徑程序將會拋出異常
*日期:2005-7-1
*作者:Pcera
*/

import java.io.*;
import java.util.*;
import java.util.zip.*;

class zipFileRelease{

private String inFilePath;
private String releaseFilePath;
private String[] FileNameArray; //存放文件名稱的數組
private ZipEntry entry;
//
private FileInputStream fileDataIn;
private FileOutputStream fileDataOut;
private ZipInputStream zipInFile;
private DataOutputStream writeData;
private DataInputStream readData;
//
private int zipFileCount = 0; //zip文件中的文件總數
private int zipPathCount = 0; //zip文件中的路徑總數

/**
*初始化函數
*初始化zip文件流、輸出文件流以及其他變數的初始化
*/
public zipFileRelease(String inpath,String releasepath){
inFilePath = inpath;
releaseFilePath = releasepath;
}

/**
*初始化讀取文件流函數
*參數:FileInputStream類
*返回值:初始化成功返回0,否則返回-1
*/
protected long initInStream(ZipInputStream zipFileA){
try{
readData = new DataInputStream(zipFileA);
return 0;
}catch(Exception e){
e.printStackTrace();
return -1;
}
}

/**
*測試文件路徑
*參數:zip文件的路徑和要釋放的位置
*返回值:是兩位整數,兩位數中的十位代表輸入路徑和輸出路徑(1輸入、2輸出)
* 各位數是代表絕對路徑還是相對路徑(1絕對、0相對)
* 返回-1表示路徑無效

protected long checkPath(String inPath,String outPath){
File infile = new File(inPath);
File infile = new File(outPath);

}
*/

/**
*初始化輸出文件流
*參數:File類
*返回值:初始化成功返回0,否則返回-1
*/
protected long initOutStream(String outFileA){
try{
fileDataOut = new FileOutputStream(outFileA);
writeData = new DataOutputStream(fileDataOut);
return 0;
}catch(IOException e){
e.printStackTrace();
return -1;
}
}

/**
*測試文件是否存在方法
*參數:File類
*返回值:如果文件存在返迴文件大小,否則返回-1
*/
public long checkFile(File inFileA){
if (inFileA.exists()){
return 0;
}else{
return -1;
}
}

/**
*判斷文件是否可以讀取方法
*參數:File類
*返回值:如果可以讀取返回0,否則返回-1
*/
public long checkOpen(File inFileA){
if(inFileA.canRead()){
return inFileA.length();
}else{
return -1;
}
}

/**
*獲得zip文件中的文件夾和文件總數
*參數:File類
*返回值:如果正常獲得則返回總數,否則返回-1
*/
public long getFilFoldCount(String infileA){
try{
int fileCount = 0;
zipInFile = new ZipInputStream(new FileInputStream(infileA));
while ((entry = zipInFile.getNextEntry()) != null){
if (entry.isDirectory()){
zipPathCount++;
}else{
zipFileCount++;
}
fileCount++;
}
return fileCount;
}catch(IOException e){
e.printStackTrace();
return -1;
}
}

/**
*讀取zip文件清單函數
*參數:File類
*返回值:文件清單數組
*/
public String[] getFileList(String infileA){
try{
ZipInputStream AzipInFile = new ZipInputStream(new FileInputStream(infileA));
//創建數組對象
FileNameArray = new String[(int)getFilFoldCount(infileA)];

//將文件名清單傳入數組
int i = 0;
while ((entry = AzipInFile.getNextEntry()) != null){
FileNameArray[i++] = entry.getName();
}
return FileNameArray;
}catch(IOException e){
e.printStackTrace();
return null;
}
}

/**
*創建文件函數
*參數:File類
*返回值:如果創建成功返回0,否則返回-1
*/
public long writeFile(String outFileA,byte[] dataByte){
try{
if (initOutStream(outFileA) == 0){
writeData.write(dataByte);
fileDataOut.close();
return 0;
}else{
fileDataOut.close();
return -1;
}
}catch(IOException e){
e.printStackTrace();
return -1;
}
}

/**
*讀取文件內容函數
*參數:File類
*返回值:如果讀取成功則返回讀取數據的位元組數組,如果失敗則返回空值
*/
protected byte[] readFile(ZipEntry entryA,ZipInputStream zipFileA){
try{
long entryFilelen;
if (initInStream(zipFileA) == 0){
if ((entryFilelen = entryA.getSize()) >= 0){
byte[] entryFileData = new byte[(int)entryFilelen];
readData.readFully(entryFileData,0,(int)entryFilelen);
return entryFileData;
}else{
return null;
}
}else{
return null;
}
}catch(IOException e){
e.printStackTrace();
return null;
}
}

/**
*創建目錄函數
*參數:要創建目錄的路徑
*返回值:如果創建成功則返回0,否則返回-1
*/
public long createFolder(String dir){
File file = new File(dir);
if (file.mkdirs()) {
return 0;
}else{
return -1;
}
}

/**
*刪除文件
*參數:要刪除的文件
*返回值:如果刪除成功則返回0,要刪除的文件不存在返回-2
* 如果要刪除的是個路徑則返回-3,刪除失敗則返回-1
*/
public long deleteFile(String Apath) throws SecurityException {
File file = new File(Apath.trim());
//文件或路徑不存在
if (!file.exists()){
return -2;
}
//要刪除的是個路徑
if (!file.isFile()){
return -3;
}
//刪除
if (file.delete()){
return 0;
}else{
return -1;
}
}

/**
*刪除目錄
*參數:要刪除的目錄
*返回值:如果刪除成功則返回0,刪除失敗則返回-1
*/
public long deleteFolder(String Apath){
File file = new File(Apath);
//刪除
if (file.delete()){
return 0;
}else{
return -1;
}
}

/**
*判斷所要解壓的路徑是否存在同名文件
*參數:解壓路徑
*返回值:如果存在同名文件返回-1,否則返回0
*/
public long checkPathExists(String AreleasePath){
File file = new File(AreleasePath);
if (!file.exists()){
return 0;
}else{
return -1;
}
}

/**
*刪除zip中的文件
*參數:文件清單數組,釋放路徑
*返回值:如果刪除成功返回0,否則返回-1
*/
protected long deleteReleaseZipFile(String[] listFilePath,String releasePath){
long arrayLen,flagReturn;
int k = 0;
String tempPath;
//存放zip文件清單的路徑
String[] pathArray = new String[zipPathCount];
//刪除文件
arrayLen = listFilePath.length;
for(int i=0;i<(int)arrayLen;i++){
tempPath = releasePath.replace('\\','/') + listFilePath[i];
flagReturn = deleteFile(tempPath);
if (flagReturn == -2){
//什麼都不作
}else if (flagReturn == -3){
pathArray[k++] = tempPath;
}else if (flagReturn == -1){
return -1;
}
}
//刪除路徑
for(k = k - 1;k>=0;k--){
flagReturn = deleteFolder(pathArray[k]);
if (flagReturn == -1) return -1;
}
return 0;
}

/**
*獲得zip文件的最上層的文件夾名稱
*參數:zip文件路徑
*返回值:文件夾名稱,如果失敗則返回null
*/
public String getZipRoot(String infileA){
String rootName;
try{
FileInputStream tempfile = new FileInputStream(infileA);
ZipInputStream AzipInFile = new ZipInputStream(tempfile);
ZipEntry Aentry;
Aentry = AzipInFile.getNextEntry();
rootName = Aentry.getName();
tempfile.close();
AzipInFile.close();
return rootName;
}catch(IOException e){
e.printStackTrace();
return null;
}
}

/**
*釋放流,釋放佔用資源
*/
protected void closeStream() throws Exception{
fileDataIn.close();
fileDataOut.close();
zipInFile.close();
writeData.flush();
}

/**
*解壓函數
*對用戶的zip文件路徑和解壓路徑進行判斷,是否存在和打開
*在輸入解壓路徑時如果輸入"/"則在和zip文件存放的統計目錄下進行解壓
*返回值:0表示釋放成功
* -1 表示您所要解壓的文件不存在、
* -2表示您所要解壓的文件不能被打開、
* -3您所要釋放的路徑不存在、
* -4您所創建文件目錄失敗、
* -5寫入文件失敗、
* -6表示所要釋放的文件已經存在、
* -50表示文件讀取異常
*/
public long releaseHandle() throws Exception{
File inFile = new File(inFilePath);
File outFile = new File(releaseFilePath);
String tempFile;
String zipPath;
String zipRootPath;
String tempPathParent; //存放釋放路徑
byte[] zipEntryFileData;

//作有效性判斷
if (checkFile(inFile) == -1) {
return -1;}
if (checkOpen(inFile) == -1) {
return -2;}
//不是解壓再當前目錄下時對路徑作有效性檢驗
if (!releaseFilePath.equals("/")){
//解壓在用戶指定目錄下
if (checkFile(outFile) == -1) {
return -3;}
}
//獲得標准釋放路徑
if (!releaseFilePath.equals("/")) {
tempPathParent = releaseFilePath.replace('\\','/')+ "/";
}else{
tempPathParent = inFile.getParent().replace('\\','/')+ "/";
}
//獲得zip文件中的入口清單
FileNameArray = getFileList(inFilePath);
//獲得zip文件的最上層目錄
zipRootPath = getZipRoot(inFilePath);
//
fileDataIn = new FileInputStream(inFilePath);
zipInFile = new ZipInputStream(fileDataIn);
//判斷是否已經存在要釋放的文件夾
if (zipRootPath.lastIndexOf("/") > 0 ){
if (checkPathExists(tempPathParent +
zipRootPath.substring(0,zipRootPath.lastIndexOf("/"))) == -1){
return -6;
}
}else{
if (checkPathExists(tempPathParent + zipRootPath) == -1){
return -6;
}
}

//
try{
//創建文件夾和文件
int i = 0;
while ((entry = zipInFile.getNextEntry()) != null){
if (entry.isDirectory()){
//創建目錄
zipPath = tempPathParent + FileNameArray[i];
zipPath = zipPath.substring(0,zipPath.lastIndexOf("/"));
if (createFolder(zipPath) == -1){
closeStream();
deleteReleaseZipFile(FileNameArray,tempPathParent);
return -4;
}

}else{
//讀取文件數據
zipEntryFileData = readFile(entry,zipInFile);
//向文件寫數據
tempFile = tempPathParent + FileNameArray[i];
//寫入文件
if (writeFile(tempFile,zipEntryFileData) == -1){
closeStream();
deleteReleaseZipFile(FileNameArray,tempPathParent);
return -5;
}
}
i++;
}
//釋放資源
closeStream();
return 0;
}catch(Exception e){
closeStream();
deleteReleaseZipFile(FileNameArray,tempPathParent);
e.printStackTrace();
return -50;
}
}
/**
*演示函數
*根據用戶輸入的路徑對文件進行解壓
*/
public static void main(String args[]) throws Exception {

long flag; //返回標志
String inPath,releasePath;

//獲得用戶輸入信息
BufferedReader userInput = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("請輸入zip文件路徑:");
inPath = userInput.readLine();
System.out.println("請輸入保存路徑:");
releasePath = userInput.readLine();
userInput.close();

//執行解壓縮
zipFileRelease pceraZip = new zipFileRelease(inPath,releasePath);
flag = pceraZip.releaseHandle();

//出錯信息列印
if (flag == 0) System.out.println("釋放成功!!!");
if (flag == -1) System.out.println("您所要解壓的文件不存在!");
if (flag == -2) System.out.println("您所要解壓的文件不能被打開!");
if (flag == -3) System.out.println("您所要釋放的路徑不存在!");
if (flag == -4) System.out.println("您所創建文件目錄失敗!");
if (flag == -5) System.out.println("寫入文件失敗!");
if (flag == -6) System.out.println("文件已經存在!");
if (flag == -50) System.out.println("文件讀取異常!");
}
}

❻ java怎麼讀取Zip和RAR裡面的文件啊

ZipInputStream是一個指向ZIP文件的流,這個流最重要的方法就是getNextEntry方法,一個zip文件可以包含好幾個被壓縮的文件,這個方法的功能就是返回下一個目錄項,也就是返回zip文件中的下一項,並且把流指向這個目錄文件項。getNextEntry的返回值是ZipEntry,它表示zip文件中的一個項,它可以返回這個文件項的大小、名稱等。你可以根據它返回的文件大小調用ZipInputStream的read方法來讀取需要的位元組。給你一個例子:public class ZipTest {
public static void main(String args[]) throws FileNotFoundException, IOException{
ZipInputStream zis = new ZipInputStream(new FileInputStream ("c://a.zip"));//生成讀取ZIP文件的流
ZipEntry ze = zis.getNextEntry();//取得下一個文件項
long size = ze.getSize();//取得這一項的大小
FileOutputStream fos = new FileOutputStream("c://"+ze.getName());//產生輸出文件對象
for(int i= 0;i<size;i++){//循環讀取文件並寫入輸出文件對象
byte c = (byte)zis.read();
fos.write(c);
}
fos.close();
zis.close();
}
}

❼ java如何讀取壓縮包中的文本文件

壓縮包的里的文件不能直接讀取,只能先解壓縮,再讀取。
建議:可以用apache的工具類,先解壓縮成臨時文件,再讀取,最後刪除臨時文件。

❽ 怎樣用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();
}
}
}

❾ java Zip解析亂碼問題

debug一下,看看filepath輸出什麼,看看下面這個代碼
import java.io.*;
import java.util.zip.*;

public class Zip {
static final int BUFFER = 2048;
static boolean flag = false;

public static void main(String args[])throws IOException{
File file= new File("D:/Temp");
ZipSubdirectory(file);
FileInputStream file1 = new FileInputStream(ZipSubdirectory(file));
System.out.println(file1.toString());
}
//ZipSubdirectory函數將一個指定目錄(包括它子目錄)壓縮成一個同名壓縮文件(這里稱為"ORIGIN")
public static File ZipSubdirectory(File myDir)throws IOException{
//創建緩沖輸入流BufferedInputStream
BufferedInputStream origin = null;
//創建ZipOutputStream對象,將向它傳遞希望寫入文件的輸出流
File zipFile=new File("D:/"+myDir.getName()+".zip");
FileOutputStream fos=new FileOutputStream(zipFile);
ZipOutputStream out=new ZipOutputStream(new BufferedOutputStream(fos,BUFFER));
//dirContents[]獲取當前目錄(myDir)所有文件對象(包括子目錄名)
File dirContents[]=myDir.listFiles();
//創建臨時文件tempFile,使用後刪除
File tempFile=null;
try{
//處理當前目錄所有文件對象,包括子目錄
for(int i=0;i < dirContents.length; i++){
//使用遞歸方法將當前目錄的子目錄轉成一個ZIP文件,並作為一個ENTRY加進"ORIGIN"
if(dirContents[i].isDirectory()){
tempFile = ZipSubdirectory(dirContents[i]);
flag=true;
}
//如果當前文件不是子目錄
else {
tempFile=dirContents[i];
//flag標記tempFile是否由子目錄壓縮成的ZIP文件
flag = false;
}
System.out.println("Compress file: "+tempFile.getName());
FileInputStream fis = new FileInputStream(tempFile);
origin = new BufferedInputStream(fis,BUFFER);
//為被讀取的文件創建壓縮條目
ZipEntry entry = new ZipEntry(tempFile.getName());
byte data[]= new byte[BUFFER];
int count;
//在向ZIP輸出流寫入數據之前,必須首先使用out.putNextEntry(entry); 方法安置壓縮條目對象
out.putNextEntry(entry);
//向ZIP 文件寫入數據
while((count=origin.read(data,0,BUFFER))!=-1){
out.write(data,0,count);
}
//tempFile是臨時生成的ZIP文件,刪除它
if(flag==true){
flag = tempFile.delete();
System.out.println("Delete file:"+tempFile.getName()+flag);
}
//關閉輸入流
origin.close();
}
out.close();
} catch(Exception e){
System.out.println(e);
}
//遞歸返回
return zipFile;
}
}

來自

❿ 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目錄

閱讀全文

與java解析壓縮文件相關的資料

熱點內容
網路java模擬器 瀏覽:266
紅米note2現在系統版本 瀏覽:162
項目管理綱領性文件有哪些內容 瀏覽:584
如何打開e盤的word文件 瀏覽:267
基本文件有哪些 瀏覽:85
如何讓word顯示一頁 瀏覽:136
電腦word文檔怎麼保存docx文件 瀏覽:825
建德ps九折文件袋 瀏覽:659
c盤文件哪些是可以刪除的 瀏覽:395
火狐附加組件工具欄 瀏覽:471
如何批量找相同數據自動排序 瀏覽:639
網路技術有限公司需要什麼軟體 瀏覽:534
怎麼用qq找到新浪微博賬號密碼 瀏覽:569
資料庫附加5173 瀏覽:181
梁祝哪個版本最好 瀏覽:713
86版本厄運好還是嗜血 瀏覽:853
office如何設置一列數據 瀏覽:495
excel表格如何做數據的相關性分析 瀏覽:541
iphone5s無服務怎麼修 瀏覽:281
360路由器怎麼設置隱藏wifi密碼錯誤 瀏覽:98

友情鏈接