javagzip壓縮文件夾
byte[] buf = new byte[4096*2];
//建立位元組數組輸入流
ByteArrayInputStream i = new ByteArrayInputStream(buffer);
//建立gzip解壓輸入流
GZIPInputStream gzin = new GZIPInputStream(i);
int size = gzin.read(buf);
i.close();
gzin.close();
byte b[] = new byte[size];
System.array(buf,0,b,0,size);
return b;
B. 是否能用delphi的zlib解壓java gzip壓縮的字元串
可以使用 delphi 與 java 完成數據壓縮還原的交通。
不管是 java還是 delphi,演算法都有現成的控制項,關鍵是要使用同樣的壓縮協議。請參考以下資料:
在Java與Delphi間交互實現Zlib壓縮演算法
http://blog.csdn.net/hexingyeyun/article/details/8678154
C. 請問用java編寫一個壓縮程序,怎樣解決壓縮文件zip里的文件名亂碼問題!
沒做過壓縮程序,JAVA裡面的字元串使用的編碼為unicode,ZIP文件裡面用的應該是本地編碼(中文操作系統用的是GB2312)。
你可以嘗試著用類似這樣的語句:String str = ( otherStr.getBytes("GB2312") );
祝好運。
D. 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) {
}
E. 在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 ArrayList<String>extensions = new ArrayList<String>();
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("文件讀取異常!");
}
}
F. java後台怎麼接收一個gzip壓縮流,並且解析接受參數
原則上,不需要在代碼中處理zip只接收就可以。解析可以按HTTP協議自己解析,也可以使用WEB容器完成
G. java中zip壓縮和gzip壓縮的區別
一個zip可以內藏多個文件
狹義的gzip僅對單個文件壓縮,不能打包多個文件。
tar.gzip或tgz可以打包多個文件,屬於固實壓縮,壓縮比較高,但隨機存取單個文件的效率不如zip..
H. java如何壓縮成gz包
import java.io.*;
import java.util.zip.*;
public class GZIPcompress {
public static void main(String[] args) {
try {
BufferedReader in =
new BufferedReader(
new FileReader(args[0]));
BufferedOutputStream out =
new BufferedOutputStream(
new GZIPOutputStream(
new FileOutputStream("test.gz")));
System.out.println("Writing file");
int c;
while((c = in.read()) != -1)
out.write(c);
in.close();
out.close();
System.out.println("Reading file");
BufferedReader in2 =
new BufferedReader(
new InputStreamReader(
new GZIPInputStream(
new FileInputStream("test.gz"))));
String s;
while((s = in2.readLine()) != null)
System.out.println(s);
} catch(Exception e) {
e.printStackTrace();
}
}
} ///:~
I. 把純文本字元串用Gzip壓縮再轉換為Base64能有多少壓縮率
其實具體多大壓縮率要看源文件的內容,一般來說重復吵坦的單詞越多,壓縮率越高。
下面是把/usr/share/dict/words壓縮的測升數桐試程序
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.codec.binary.Base64;
public class GzipBase64Tests {
public static void main(String[] args) throws Exception {
File input = new File("/Users/matianyi/input.txt");
File output = new File("/Users/matianyi/output.txt");
if (!input.exists()) {
System.out.println("input file not exists!");
return;
}
if (output.exists()) {
output.delete();
}
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
GZIPOutputStream gout = new GZIPOutputStream(buffer);
FileInputStream in = new FileInputStream(input);
long t1 = System.currentTimeMillis();
byte[] buf = new byte[1024];
int total=0;
int rd;
while ((rd = in.read(buf)) != -1) {
total += rd;
gout.write(buf,0, rd);
}
gout.close();
in.close();
byte[] result = buffer.toByteArray();
long t2 = System.currentTimeMillis();
String base64 = Base64.encodeBase64String(result);
long t3 = System.currentTimeMillis();
System.out.printf("raw %d -> gzip %d -> base64 %d, time1 %dms, time2 %dms"畢森, total, result.length, base64.length(), t2-t1, t3-t2);
}
}
輸出為: raw 2493109 -> gzip 753932 -> base64 1005244, time1 225ms, time2 43ms
壓縮了50%。
J. Java數據壓縮格式程序設計方法
GZIP壓縮格式簡介在JDK API中 同樣定義了多種類型用於創建和解除GZIP壓縮格式數據文件的通用對象和方法 用於基於JDK編寫GZIP壓縮數據管理程序 GZIP壓縮格式是在Sun Solaris操作系統中廣泛採用的壓縮數據格式 由於在數據壓縮過程中可以採用多種類型的壓縮演算法 因此 壓縮文件的壓縮比很高 另外 在創建的壓縮文件中 定義了用於表述時間和文件屬主的時戳(Time Stamp) 可以使文件方便地在網路中傳輸和交換 GZIP壓縮數據文件由一系列的數字構成 而各數字對應如下描述壓縮文件信息的欄位 ID 預設值 用於標識GZIP壓縮格式 ID 預設值 用於標識GZIP壓縮格式 CM 採用的壓縮方法 其值為 ~ 是保留值 標識採用 deflate 壓縮方法 FLG 用於標識各佔用位的標志 MTIME 記錄了最近修改時間 XFL 用於標識採用壓縮演算法的選項 OS 定義了操作系統類孝消告型 XLEN 定義了附加信息段的長度 M 壓縮文件說明信息 CRC 記錄了CRC 演算法採用的循環冗餘校驗值 上述信息完整描述了GZIP壓縮格式數據 當然 基於JDK開發的壓縮數據管理程序 不需要明確知道上述壓縮數據定義格式 只需要創建相應的管理對象並調用這些對象中定義的方法即可 JDK API中ZIP壓縮格式支持對象GZIP壓縮格式是在JDK API中定義支持的另外一種數據壓縮格式 由上面橋仿介紹的GZIP格式數據壓縮方法可知 GZIP壓縮格式具有更大的壓縮比 因此 在Unix操作系統中 這種類型的數據壓縮形式的應用十分普及 與JDK API對ZIP壓縮格式的支持不同 在JDK API中 只定義了GZIPInputStream和GZIPOutputStream兩種類型的流(Stream)對象 用於在基於流的數據傳輸過程中實現數據壓縮 這兩個對象的繼承定義結構如下所示 java lang Object|+ java io InputStream|+ java io FilterInputStream|+ java util zip InflaterInputStream|+ java util zip GZIPInputStream(java util zip GZIPOutputStream)巧明以採用GZIP格式進行數據輸入處理GZIPInputStream對象為例 由上述對象的繼承定義結構可以看出 該對象繼承了InflaterInputStream流對象 需要說明的是 在ZIP壓縮包中 定義了Inflater和Deflater兩個對象 用於基於ZLIB壓縮庫實現多種格式的數據壓縮和解壓縮 因此 InflaterInputStream流對象的作用是採用ZLIB庫作為數據壓縮管理的引擎 而GZIPInputStream對象則進一步將流的數據加工進行細化 用於讀取GZIP格式的壓縮數據 同理 GZIPOutputStream對象用於創建GZIP格式的壓縮數據文件 下面 將對兩個對象的定義內容進行說明 ●GZIPInputStream對象定義結構 java util zip GZIPInputStream靜態成員變數 protected CRC crc 用於說明採用的數據壓縮演算法為CRC protected boolean eos 說明輸入流對象結束讀取輸入數據 構造方法 GZIPInputStream(InputStream in) 採用默認的緩沖區位元組數創建輸入流對象 GZIPInputStream(InputStream in int size) 創建由整數類型變數size指定緩沖區位元組數的輸入流對象 成員方法 該對象只定義了如下兩個成員方法 void close() 關閉輸入流對象 int read(byte[] buf int off int len) 讀取輸入流的數據到buf位元組數組中 ●GZIPOutputStream對象定義結構 java util zip GZIPOutputStream靜態成員變數 protected CRC crc 用於說明採用的數據壓縮演算法為CRC 構造方法 GZIPOutputStream(OutputStream out) 採用默認的緩沖區位元組數創建輸出流對象 GZIPOutputStream(OutputStream out int size) 創建由整數類型變數size指定緩沖區位元組數的輸出流對象 成員方法 void close() 關閉輸出流對象 void finish() 結束數據輸出 但不關閉輸出流對象 void write(byte[] buf int off int len) 將位元組數組buf中的內容壓縮輸出到輸出流對象中 創建GZIP壓縮格式文件實例經過前面對JDK API中創建GZIP壓縮格式文件的相關對象的結構 成員方法定義形式的說明 讀者一定會問如何應用這些對象和對象中定義的成員方法呢?請讀者看下面的實例代碼 //ZipDemo javaimport java io *; import java util zip *; public class GZIPDemo { public static void main(String[] args) { if (args length != ) { System out println("Usage:java GZIPDemo SourceFile DestnFile" + args length); System exit( ); } try { int number; //打開需壓縮文件作為文件輸入流 FileInputStream fin = new FileInputStream(args[ ]); //建立壓縮文件輸出流FileOutputStream fout=new FileOutputStream(args[ ]); //建立GZIP壓縮輸出流 GZIPOutputStream gzout=new GZIPOutputStream(fout); //設定讀入緩沖區尺寸byte[] buf=new byte[ ]; while ((number = fin read(buf)) != ) gzout write(buf number); gzout close(); fout close(); fin close(); }catch(IOException e) { System out println(e); } } }上面的程序用於將命令行中指定的文件SourceFile進行壓縮 創建GZIP格式的壓縮文件DestnFile 在該程序的實現代碼中 首先創建用於進行文件輸入和輸出的FileInputStream和FileOutputStream對象 並以FileOutputStream對象實例為參數創建GZIPOutputStream對象實例 從而為創建GZIP格式壓縮文件建立數據流基礎 在隨後的代碼中 利用FileInputStream對象中定義的read方法 從源文件中讀取待壓縮文件的內容 同時利用GZIPOutputStream對象中定義的write方法將壓縮後的數據寫出到輸出文件中 從而實現數據文件的GZIP格式壓縮處理 在Java中創建GZIP格式壓縮文件的方法很簡單 並且利用WinZip WinRAR等類型的壓縮管理軟體均能夠打開創建的GZIP格式的壓縮文件 那麼 如何利用JDK API中定義的對象將被壓縮的文件解壓縮呢?請讀者看下一節的內容 GZIP格式文件解壓縮實例下面的程序用於將利用JDK API中定義對象的成員方法 將GZIP格式壓縮文件進行解壓縮 從而恢復壓縮原始文件 //UnGZIPDemo javaimport java io *; import java util zip *; public class UnGZIPDemo { public static void main(String[] args) { if (args length != ) { System out println("Usage:java UnGZIPDemo GZIPFile DestnFile"); System exit( ); } try { int number;//建立GZIP壓縮文件輸入流 FileInputStream fin=new FileInputStream(args[ ]); //建立GZIP解壓工作流 GZIPInputStream gzin=new GZIPInputStream(fin); //建立解壓文件輸出流 FileOutputStream fout=new FileOutputStream(args[ ]); //設定讀入緩沖區尺寸byte[] buf=new byte[ ]; while ((nnumber=gzin read(buf buf length)) != ) fout write(buf nnumber); gzin close(); fout close(); fin close(); }catch(IOException e) { System out println(e); } } }在GZIP格式壓縮文件解壓縮程序代碼中 仍然首先創建FileInputStream和FileOutputStream對象 並基於創建的FileInputStream對象創建GZIPInputStream對象 在隨後的代碼中 調用GZIPInputStream對象中定義的read方法 在從壓縮文件中讀取數據內容並進行解壓縮處理後 將解除壓縮後的數據內容利用文件輸出流對象進行輸出 從而實現數據文件的解壓縮處理 小 lishixin/Article/program/Java/hx/201311/27034