⑴ java端用GZIPOutputStream壓縮的數據,通過HTTP POST到PHP寫的後台,怎麼不能解壓
GZIPOutputStream和PHP的gzuncompress配合得不好,似乎是Java產生的數據頭在PHP那邊認不出來。用DeflaterOutputStream來取代GZIPOutputStream。
⑵ 在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("文件讀取異常!");
}
}
⑶ 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) {
}
⑷ 如何在java REST API中用GZip和Jersey壓縮相應
有許多情景當你的REST api提供的相應是非常長的,並且我們都知道傳遞速度和貸款在移動設備/網路上是多重要。當開發支持REST apis的移動app的時候,我認為首要的性能最優化的點就是需要解決。猜猜是什麼?因為響應式文本,因此我們能壓縮這些文本。而且隨著當前的只能手機和平板的能力,在客戶端解壓文本應該不是個大問題...因此在這篇文章中,如果你使用java的Jersey構建它,我將介紹你怎麼能有選擇性的壓縮REST API響應,這個Jersey事JAX-RS的映射實現(還有更多)...
1.Jersey過濾器和攔截器
啊,感謝Jersey的強大的過濾器和攔截器特性,這個實現是相當容易的。然後過濾器是主要打算來維護像HTTP headers,URIs和/或HTTP methods的request和response的參數,攔截器是維護實體,通過維護實體的輸入/輸出流。
但是對於壓縮將使用一個GZip WriterInterceptor,一個寫攔截器被用於這種情況,在那個類里,實體被寫到"wire",當在這種情況中時,它在伺服器這邊,這就意味著輸出一個響應實體。
1.1GZip Writer Interceptor
那讓我們來看看我們的GZip Writer Interceptor吧:
GZip Writer Interceptor
package org.codingpedia.demo.rest.interceptors;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext;
@Provider
@Compress
public class GZIPWriterInterceptor implements WriterInterceptor {
@Override
public void aroundWriteTo(WriterInterceptorContext context)
throws IOException, WebApplicationException {
MultivaluedMap<String,Object> headers = context.getHeaders();
headers.add("Content-Encoding", "gzip");
final OutputStream outputStream = context.getOutputStream();
context.setOutputStream(new GZIPOutputStream(outputStream));
context.proceed();
}
}
注意:
它實現了WriterInterceptor,這是一個寫攔截器的消息體的介面,這個介麵包裝調用javax.ws.rs.ext.MessageBodyWriter.writeTo
供應商實現WriterInterceptor協議必須要麼以編程方式注冊進一個JAX-RS運行環境,要麼必須用@Provider註解來註解在一個提供商掃描語句期間自動的被JAX-RS運行環境發現。
@Compress是綁定註解的名稱,在接下來的段落中我們將更詳細的討論它
「攔截器從WriterInterceptorContext中獲得一個輸出流並且設置一個新的用原始的GZIP包裝器包裝的輸出流。在所有的攔截器被執行以後,輸出流最終設置WriterInterceptorContext將用於序列化實體。在上面的例子中,實體位元組將被寫到GZIPOutputStream中,這個類將壓縮流數據,然後把他們寫到原始輸出流。原始流總是把數據寫到wire中。當攔截器被用在伺服器上時,原始輸出流會把數據寫到底層伺服器容器的流中,然後發送響應給客戶端。」
「重載方法aroundWriteTo()獲取WriterInterceptorContextz作為參數。這個上下文包括請求頭參數getters和setters,請求屬性,實體,實體流和其它屬性;當你壓縮你的響應時,你應當設置'Content-Encoding'頭位gzip」
1.2 壓縮註解
過濾器和攔截器能被綁定名字。名稱綁定是一種概念,這種概念就是允許告訴一個JAX-RS的運行時,一個只為特定資源方法的特定的過濾器或者攔截器將被執行。當一個過濾器或者攔截器只對一些特定的資源方法限制,那我們就認為它是名稱綁定。過濾器和攔截器沒有這樣的限制就被稱作global。在我們的例子中我們已經構建了@Compress註解:
Compress annotation
package org.codingpedia.demo.rest.interceptors;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.ws.rs.NameBinding;
//@Compress annotation is the name binding annotation
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
public @interface Compress {}
而且用它來標記在資源上的方法,這個方法應該是被壓縮的(eg:當GET-ing的時候,所有的博客用PodcastsResource)
@Compress annotation在資源方法上的使用
@Component
@Path("/podcasts")
public class PodcastsResource {
@Autowired
private PodcastService podcastService;
...........................
/*
* *********************************** READ ***********************************
*/
/**
* Returns all resources (podcasts) from the database
*
* @return
* @throws IOException
* @throws JsonMappingException
* @throws JsonGenerationException
* @throws AppException
*/
@GET
@Compress
@Proces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Podcast> getPodcasts(
@QueryParam("orderByInsertionDate") String orderByInsertionDate,
@QueryParam("numberDaysToLookBack") Integer numberDaysToLookBack)
throws IOException,AppException {
List<Podcast> podcasts = podcastService.getPodcasts(
orderByInsertionDate, numberDaysToLookBack);
return podcasts;
}
...........................
}
2.測試
2.1SOAPui
好了,如果你正在用SOAPui測試,你能使用下面的請求違反PodcastsResource
Reqest:
請求例子:
GET http://localhost:8888/demo-rest-jersey-spring/podcasts/?orderByInsertionDate=DESC HTTP/1.1
Accept-Encoding: gzip,deflate
Accept: application/json, application/xml
Host: localhost:8888
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)
Response:
被壓縮的json響應,通過SOAPui自動的解壓縮
HTTP/1.1 200 OK
Content-Type: application/json
Content-Encoding: gzip
Content-Length: 409
Server: Jetty(9.0.7.v20131107)
[
{
"id": 2,
"title": "Quarks & Co - zum Mitnehmen",
"linkOnPodcastpedia": "http://www.podcastpedia.org/quarks",
"feed": "http://podcast.wdr.de/quarks.xml",
"description": "Quarks & Co: Das Wissenschaftsmagazin",
"insertionDate": "2014-10-29T10:46:13.00+0100"
},
{
"id": 1,
"title": "- The Naked Scientists Podcast - Stripping Down Science",
"linkOnPodcastpedia": "http://www.podcastpedia.org/podcasts/792/-The-Naked-Scientists-Podcast-Stripping-Down-Science",
"feed": "feed_placeholder",
"description": "The Naked Scientists flagship science show brings you a lighthearted look at the latest scientific breakthroughs, interviews with the world top scientists, answers to your science questions and science experiments to try at home.",
"insertionDate": "2014-10-29T10:46:02.00+0100"
}
]
SOAPui接受Content-type:gzip頭,我們在GZIPWriterIntercepter中添加了並且自動的解壓了響應並且用人眼可讀的方式展示出來。
好了,就這些了。你已經了解了Jersey如何讓它直接壓縮REST api響應了。
⑸ 如何解壓.tar.gz gzip gz 類型文檔
java解壓縮.gz .zip .tar.gz等格式的壓縮包方法總結
1、.gz文件是linux下常見的壓縮格式。使用 java.util.zip.GZIPInputStream即可,壓縮是 java.util.zip.GZIPOutputStream
1 public static void unGzipFile(String sourcedir) {
2 String ouputfile = "";
3 try {
4 //建立gzip壓縮文件輸入流
5 FileInputStream fin = new FileInputStream(sourcedir);
6 //建立gzip解壓工作流
7 GZIPInputStream gzin = new GZIPInputStream(fin);
8 //建立解壓文件輸出流
9 ouputfile = sourcedir.substring(0,sourcedir.lastIndexOf('.'));
10 ouputfile = ouputfile.substring(0,ouputfile.lastIndexOf('.'));
11 FileOutputStream fout = new FileOutputStream(ouputfile);
12
13 int num;
14 byte[] buf=new byte[1024];
15
16 while ((num = gzin.read(buf,0,buf.length)) != -1)
17 {
18 fout.write(buf,0,num);
19 }
20
21 gzin.close();
22 fout.close();
23 fin.close();
24 } catch (Exception ex){
25 System.err.println(ex.toString());
26 }
27 return;
28 }
2、zip文件,使用java.util.zip.ZipEntry 和 java.util.zip.ZipFile
1 /**
2 * 解壓縮zipFile
3 * @param file 要解壓的zip文件對象
4 * @param outputDir 要解壓到某個指定的目錄下
5 * @throws IOException
6 */
7 public static void unZip(File file,String outputDir) throws IOException {
8 ZipFile zipFile = null;
9
10 try {
11 Charset CP866 = Charset.forName("CP866"); //specifying alternative (non UTF-8) charset
12 //ZipFile zipFile = new ZipFile(zipArchive, CP866);
13 zipFile = new ZipFile(file, CP866);
14 createDirectory(outputDir,null);//創建輸出目錄
15
16 Enumeration<?> enums = zipFile.entries();
17 while(enums.hasMoreElements()){
18
19 ZipEntry entry = (ZipEntry) enums.nextElement();
20 System.out.println("解壓." + entry.getName());
21
22 if(entry.isDirectory()){//是目錄
23 createDirectory(outputDir,entry.getName());//創建空目錄
24 }else{//是文件
25 File tmpFile = new File(outputDir + "/" + entry.getName());
26 createDirectory(tmpFile.getParent() + "/",null);//創建輸出目錄
27
28 InputStream in = null;
29 OutputStream out = null;
30 try{
31 in = zipFile.getInputStream(entry);;
32 out = new FileOutputStream(tmpFile);
33 int length = 0;
34
35 byte[] b = new byte[2048];
36 while((length = in.read(b)) != -1){
37 out.write(b, 0, length);
38 }
39
40 }catch(IOException ex){
41 throw ex;
42 }finally{
43 if(in!=null)
44 in.close();
45 if(out!=null)
46 out.close();
47 }
48 }
49 }
50
51 } catch (IOException e) {
52 throw new IOException("解壓縮文件出現異常",e);
53 } finally{
54 try{
55 if(zipFile != null){
56 zipFile.close();
57 }
58 }catch(IOException ex){
59 throw new IOException("關閉zipFile出現異常",ex);
60 }
61 }
62 }
63
64 /**
65 * 構建目錄
66 * @param outputDir
67 * @param subDir
68 */
69 public static void createDirectory(String outputDir,String subDir){
70 File file = new File(outputDir);
71 if(!(subDir == null || subDir.trim().equals(""))){//子目錄不為空
72 file = new File(outputDir + "/" + subDir);
73 }
74 if(!file.exists()){
75 if(!file.getParentFile().exists())
76 file.getParentFile().mkdirs();
77 file.mkdirs();
78 }
79 }
3、.tar.gz文件可以看做先用tar打包,再使用gz進行壓縮。
使用org.apache.tools.tar.TarEntry; org.apache.tools.tar.TarInputStream 和 org.apache.tools.tar.TarOutputStream
1 //------------------------------------------------------------------------------------------------------
2 /**
3 * 解壓tar.gz 文件
4 * @param file 要解壓的tar.gz文件對象
5 * @param outputDir 要解壓到某個指定的目錄下
6 * @throws IOException
7 */
8 public static void unTarGz(File file,String outputDir) throws IOException{
9 TarInputStream tarIn = null;
10 try{
11 tarIn = new TarInputStream(new GZIPInputStream(
12 new BufferedInputStream(new FileInputStream(file))),
13 1024 * 2);
14
15 createDirectory(outputDir,null);//創建輸出目錄
16
17 TarEntry entry = null;
18 while( (entry = tarIn.getNextEntry()) != null ){
19
20 if(entry.isDirectory()){//是目錄
21 entry.getName();
22 createDirectory(outputDir,entry.getName());//創建空目錄
23 }else{//是文件
24 File tmpFile = new File(outputDir + "/" + entry.getName());
25 createDirectory(tmpFile.getParent() + "/",null);//創建輸出目錄
26 OutputStream out = null;
27 try{
28 out = new FileOutputStream(tmpFile);
29 int length = 0;
30
31 byte[] b = new byte[2048];
32
33 while((length = tarIn.read(b)) != -1){
34 out.write(b, 0, length);
35 }
36
37 }catch(IOException ex){
38 throw ex;
39 }finally{
40
41 if(out!=null)
42 out.close();
43 }
44 }
45 }
46 }catch(IOException ex){
47 throw new IOException("解壓歸檔文件出現異常",ex);
48 } finally{
49 try{
50 if(tarIn != null){
51 tarIn.close();
52 }
53 }catch(IOException ex){
54 throw new IOException("關閉tarFile出現異常",ex);
55 }
56 }
57 }
使用到的包頭有:
1 import java.io.BufferedInputStream;
2 import java.io.File;
3 import java.io.FileInputStream;
4 import java.io.FileOutputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.OutputStream;
8
9 import java.nio.charset.Charset;
10 import java.util.Enumeration;
11 import java.util.zip.GZIPInputStream;
12 import java.util.zip.ZipEntry;
13 import java.util.zip.ZipFile;
14
15 import org.apache.tools.tar.TarEntry;
16 import org.apache.tools.tar.TarInputStream;
17 import org.apache.tools.tar.TarOutputStream;
⑹ 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中的出錯就表示,其實你去錯了!
⑺ 是否能用delphi的zlib解壓java gzip壓縮的字元串
可以使用 delphi 與 java 完成數據壓縮還原的交通。
不管是 java還是 delphi,演算法都有現成的控制項,關鍵是要使用同樣的壓縮協議。請參考以下資料:
在Java與Delphi間交互實現Zlib壓縮演算法
http://blog.csdn.net/hexingyeyun/article/details/8678154
⑻ C# 中GZIP 壓縮,求在JAVA中解壓代碼
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;
⑼ java怎麼用Gzip實現文件的壓縮和解壓縮的
代碼:
⑽ 如何解壓java 壓縮的 gzip字元串
一個zip可以內藏多個文件
狹義的gzip僅對單個文件壓縮,不能打包多個文件。
tar.gzip或tgz可以打包多個文件,屬於固實壓縮,壓縮比較高,但隨機存取單個文件的效率不如zip..