javagzip,javagzip解壓

本文目錄一覽:

java中zip壓縮和gzip壓縮的區別

一個zip可以內藏多個文件

狹義的gzip僅對單個文件壓縮,不能打包多個文件。

tar.gzip或tgz可以打包多個文件,屬於固實壓縮,壓縮比較高,但隨機存取單個文件的效率不如zip..

在java中,gzip 壓縮和解壓多個文件?

直接編譯運行!!!

不知道你是要查看壓縮文件還是要解壓文件,所以發上來兩個。

第一個可以查看各個壓縮項目;

第二個可以解壓文件。

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import java.util.*;

import java.util.zip.*;

import javax.swing.*;

import javax.swing.filechooser.FileFilter;

class ZipTest {

public static void main(String[] args) {

ZipTestFrame frame = new ZipTestFrame();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

}

}

class ZipTestFrame extends JFrame {

private JComboBox fileCombo;

private JTextArea fileText;

private String zipname;

public ZipTestFrame() {

setTitle(“ZipTest”);

setSize(400,300);

JMenuBar menuBar = new JMenuBar();

JMenu menu = new JMenu(“File”);

JMenuItem openItem = new JMenuItem(“Open”);

menu.add(openItem);

openItem.addActionListener(new OpenAction());

JMenuItem exitItem = new JMenuItem(“Exit”);

menu.add(exitItem);

exitItem.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent event) {

System.exit(0);

}

});

menuBar.add(menu);

setJMenuBar(menuBar);

fileText = new JTextArea();

fileCombo = new JComboBox();

fileCombo.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent event) {

loadZipFile((String)fileCombo.getSelectedItem());

}

});

add(fileCombo, BorderLayout.SOUTH);

add(new JScrollPane(fileText), BorderLayout.CENTER);

}

public class OpenAction implements ActionListener {

public void actionPerformed(ActionEvent event) {

JFileChooser chooser = new JFileChooser();

chooser.setCurrentDirectory(new File(“.”));

ExtensionFileFilter filter = new ExtensionFileFilter();

filter.addExtension(“.zip”);

filter.addExtension(“.jar”);

filter.setDescription(“ZIP archives”);

chooser.setFileFilter(filter);

int r = chooser.showOpenDialog(ZipTestFrame.this);

if(r == JFileChooser.APPROVE_OPTION) {

zipname = chooser.getSelectedFile().getPath();

scanZipFile();

}

}

}

public void scanZipFile() {

fileCombo.removeAllItems();

try {

ZipInputStream zin = new ZipInputStream(new FileInputStream(zipname));

ZipEntry entry;

while((entry = zin.getNextEntry()) != null) {

fileCombo.addItem(entry.getName());

zin.closeEntry();

}

zin.close();

} catch(IOException e) {

e.printStackTrace();

}

}

public void loadZipFile(String name) {

try {

ZipInputStream zin = new ZipInputStream(new FileInputStream(zipname));

ZipEntry entry;

fileText.setText(“”);

while((entry = zin.getNextEntry()) != null) {

if(entry.getName().equals(name)) {

BufferedReader in = new BufferedReader(new InputStreamReader(zin));

String line;

while((line = in.readLine())!=null) {

fileText.append(line);

fileText.append(“\n”);

}

}

zin.closeEntry();

}

zin.close();

} catch(IOException e) {

e.printStackTrace();

}

}

}

class ExtensionFileFilter extends FileFilter {

private String description = “”;

private ArrayListStringextensions = new ArrayListString();

public void addExtension(String extension) {

if(!extension.startsWith(“.”))

extension = “.” + extension;

extensions.add(extension.toLowerCase());

}

public void setDescription(String aDescription) {

description = aDescription;

}

public String getDescription() {

return description;

}

public boolean accept(File f) {

if(f.isDirectory()) return true;

String name = f.getName().toLowerCase();

for(String e : extensions)

if(name.endsWith(e))

return true;

return false;

}

}

///////////////////////////////////////////////////////////

/**

*類名:zipFileRelease

*說明:一個zip文件解壓類

*介紹:主要的zip文件釋放方法releaseHandle()

* 用ZipInputStream類和ZipEntry類將zip文件的入口清單列舉出來,然後

* 根據用戶提供的輸出路徑和zip文件的入口進行組合通過DataOutputStream

* 和File類進行文件的創建和目錄的創建,創建文件時的文件數據是通過

* ZipInputStream類、ZipEntry類、InputStream類之間的套嵌組合獲得的。

*注意:如果zip文件中包含中文路徑程序將會拋出異常

*/

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 與 c# GZIp

聽他瞎吹,關於Java方面我不了解,但是對於.net方面,使用GZip進行壓縮的並沒有在前邊多出4個位元組!我也很奇怪,所以進行了測試,(我測試了4.0和4.52兩個版本)

至於為什麼是四個位元組,非固定塊加密時(固定塊表示每塊長度固定),一般要說明其塊長度,而這個一般使用的是4個位元組的整數(.net中的Int32/int),不同語言的可能定義也不同,但這個4個字元來源於GZip的規定用四個位元組來說明長度(低位在前,高位在後)。所以不管是哪個語言,不管4個位元組是叫int(.net)還是叫long(C++)都必須使用4個位元組的。

但從頭到尾均沒有出現在前邊有四個位元組的說法!且我也沒有聽說過,因為GZip是一種壓縮演算法,這種演算法是否在前邊存在有位元組長度的說明,是演算法規定好的!所以我的第一反應就是不可能的——GZip有自己的標準,難道某個語言實現時不按標準來嗎?

那麼是不是有可能出現兩種語言無法解壓的情況呢?標準之所以稱之為標準,兩種語言實現時必須按相同的標準,換句話來說標準本身就必須在不同的語言實現達到一個統一轉換的過程。不可能用.net的MD5到Java中驗證不了,也不可能.net的GZip壓縮到Java中解壓不了!

那麼為什麼會出現某些人說的無法解壓的情況呢?因為死讀書的程序員導致的!標準是標準,但標準中也往往有不同的選擇!比如在GZip壓縮中就有快速/優化兩種壓縮方式,當然這兩處方式。而不在同語言中所使用的默認壓縮方式不同,另一種語言中的默認解壓方式不同,就會出現無法匹配的情況。

我舉個例子吧,好多人在問DES加解密Java與.net不對稱,我覺得不可能,後來才知道,一邊默認壓縮,另一連默認解壓,問題在於.net默認是CBC格式,而Java中恰恰不是!這就導致加解密錯誤的原因。事實上我即使在不跨語言時也會經常指明格式,所以我倒是沒有遇到這種情況。

比如 GZipStream stream = new GZipStream(baseStream, CompressLevel.Faster,true);試試這個,但不管怎麼說,你若去掉四個位元組,在Android中的出錯就表示,其實你去錯了!

java程序如何批量解壓GZIP壓縮包

給你一段單個文件解壓gzip文件代碼

批量解壓的話 File f = new File(“要解壓的文件夾目錄”);

String paths[] = f.list(); // 取得文件夾下的文件

然後循環調用下面的方法就可以了。

try {

// Open the compressed file

String inFilename = “infile.gzip”;

GZIPInputStream in = new GZIPInputStream(new FileInputStream(inFilename));

// Open the output file

String outFilename = “outfile”;

OutputStream out = new FileOutputStream(outFilename);

// Transfer bytes from the compressed file to the output file

byte[] buf = new byte[1024];

int len;

while ((len = in.read(buf)) 0) {

out.write(buf, 0, len);

}

// Close the file and stream

in.close();

out.close();

} catch (IOException e) {

}

原創文章,作者:OKCH,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/137476.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
OKCH的頭像OKCH
上一篇 2024-10-04 00:17
下一篇 2024-10-04 00:17

相關推薦

  • JavaGzip解壓詳解

    一、Gzip的基本概念 1、Gzip的作用 Gzip是一種數據壓縮格式,通過在數據中替換重複的信息,從而減少數據傳輸量,提高傳輸效率。在數據傳輸中,伺服器端通常會使用Gzip對傳輸…

    編程 2024-12-22

發表回復

登錄後才能評論