Java壓縮

在最近的項目中,我們不得不做一些我個人從未真正看過的事情。 壓縮。 我們需要拍幾個文件和圖像,將它們壓縮并提供給FTP使用,是的,總有一天,感覺確實回到了90年代。 除了過去的FTP之行外,它還是一個很好的機會,可以花一點時間在這個問題上。

壓縮檔案

因此,在通常的IO類BufferedInputStream , FileOutputStream和File上面有:

  • ZipInputStream –輸入流,用于讀取ZIP文件格式的文件。 與ZipFile不同,不緩存Zip條目。
  • ZipOutputStream –用于以ZIP文件格式寫入文件的輸出流。 這有一個默認的內部緩沖區512,可以使用BufferedOutputStream來增加它。
  • ZipEntry –表示一個zip文件中的條目。
  • ZipFile –用于從zip文件讀取條目。 條目被緩存。
  • CRC32 –用于計算數據流的CRC-32。

下面的示例顯示了如何在有和沒有校驗和的情況下壓縮和解壓縮文件夾中的文件:

package javaitzen.blog;import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;/*** The Class FileCompressionUtil.*/
public class FileCompressionUtil {private static final String PATH_SEP = "\\";public static final int BUFFER = 2048;private FileCompressionUtil() {}/*** Zip files in path.* * @param zipFileName the zip file name* @param filePath the file path* @throws IOException Signals that an I/O exception has occurred.*/public static void zipFilesInPath(final String zipFileName, final String filePath) throws IOException {final FileOutputStream dest = new FileOutputStream(zipFileName);final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));try {byte[] data = new byte[BUFFER];final File folder = new File(filePath);final List< String > files = Arrays.asList(folder.list());for (String file : files) {final FileInputStream fi = new FileInputStream(filePath + PATH_SEP + file);final BufferedInputStream origin = new BufferedInputStream(fi, BUFFER);out.putNextEntry(new ZipEntry(file));int count;while ((count = origin.read(data, 0, BUFFER)) != -1) {out.write(data, 0, count);}origin.close();fi.close();}} finally {out.close();dest.close();}}/*** Zip with checksum. CRC32* * @param zipFileName the zip file name* @param folderPath the folder path* @return the checksum* @throws IOException Signals that an I/O exception has occurred.*/public static long zipFilesInPathWithChecksum(final String zipFileName, final String folderPath) throws IOException {final FileOutputStream dest = new FileOutputStream(zipFileName);final CheckedOutputStream checkStream = new CheckedOutputStream(dest, new CRC32());final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(checkStream));try {byte[] data = new byte[BUFFER];final File folder = new File(folderPath);final List< String > files = Arrays.asList(folder.list());for (String file : files) {final FileInputStream fi = new FileInputStream(folderPath + PATH_SEP + file);final BufferedInputStream origin = new BufferedInputStream(fi, BUFFER);out.putNextEntry(new ZipEntry(file));int count;while ((count = origin.read(data, 0, BUFFER)) != -1) {out.write(data, 0, count);}origin.close();}} finally {out.close();checkStream.close();dest.flush();dest.close();}return checkStream.getChecksum().getValue();}/*** Unzip files to path.* * @param zipFileName the zip file name* @param fileExtractPath the file extract path* @throws IOException Signals that an I/O exception has occurred.*/public static void unzipFilesToPath(final String zipFileName, final String fileExtractPath) throws IOException {final FileInputStream fis = new FileInputStream(zipFileName);final ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));try {ZipEntry entry;while ((entry = zis.getNextEntry()) != null) {int count;byte[] data = new byte[BUFFER];final FileOutputStream fos = new FileOutputStream(fileExtractPath + PATH_SEP + entry.getName());final BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);while ((count = zis.read(data, 0, BUFFER)) != -1) {dest.write(data, 0, count);}dest.flush();dest.close();}} finally {fis.close();zis.close();}}/*** Unzip files to path with checksum. CRC32* * @param zipFileName the zip file name* @param fileExtractPath the file extract path* @param checksum the checksum* @return true, if checksum matches;* @throws IOException Signals that an I/O exception has occurred.*/public static boolean unzipFilesToPathWithChecksum(final String zipFileName, final String fileExtractPath, final long checksum) throws IOException {boolean checksumMatches = false;final FileInputStream fis = new FileInputStream(zipFileName);final CheckedInputStream checkStream = new CheckedInputStream(fis, new CRC32());final ZipInputStream zis = new ZipInputStream(new BufferedInputStream(checkStream));try {ZipEntry entry = null;while ((entry = zis.getNextEntry()) != null) {int count;byte[] data = new byte[BUFFER];final FileOutputStream fos = new FileOutputStream(fileExtractPath + PATH_SEP + entry.getName());final BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);while ((count = zis.read(data, 0, BUFFER)) != -1) {dest.write(data, 0, count);}dest.flush();dest.close();}} finally {zis.close();fis.close();checkStream.close();}if(checkStream.getChecksum().getValue() == checksum) {checksumMatches = true;}return checksumMatches;}}

壓縮物件

我們最終沒有使用對象壓縮,但無論如何我還是看了一下。 我做了一些通用的compress / expand util,不知道它是否有用。 我將輸入參數保留為OutputStream和InputStream,因為從理論上講,它可以與從套接字通信到字符串處理的任何流實現一起使用。

這里使用與壓縮相關的類:

  • GZIPInputStream –一個輸入流過濾器,用于讀取GZIP文件格式的壓縮數據。
  • GZIPOutputStream –輸出流過濾器,用于以GZIP文件格式寫入壓縮數據。
  • 默認內部緩沖區為512,如果需要更多,請使用BufferedOutputStream 。
package javaitzen.blog;import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;/*** The Class ObjectCompressionUtil.* * @param <T> the generic type of the serializable object to be compressed*/
public class ObjectCompressionUtil<T extends Serializable> {/*** Compress object.* * @param objectToCompress the object to compress* @param outstream the outstream* @return the compressed object* @throws IOException Signals that an I/O exception has occurred.*/public T compressObject(final T objectToCompress, final OutputStream outstream) throws IOException {final GZIPOutputStream gz = new GZIPOutputStream(outstream);final ObjectOutputStream oos = new ObjectOutputStream(gz);try {oos.writeObject(objectToCompress);oos.flush();return objectToCompress;}finally {oos.close();outstream.close();}}/*** Expand object.* * @param objectToExpand the object to expand* @param instream the instream* @return the expanded object* @throws IOException Signals that an I/O exception has occurred.* @throws ClassNotFoundException the class not found exception*/public T expandObject(final T objectToExpand, final InputStream instream) throws IOException,ClassNotFoundException {final GZIPInputStream gs = new GZIPInputStream(instream);final ObjectInputStream ois = new ObjectInputStream(gs);try {@SuppressWarnings("unchecked")T expandedObject = (T) ois.readObject();return expandedObject;} finally {gs.close();ois.close();}}}

參考:來自Zen的 JCG合作伙伴 Brian的Java壓縮 技術 。

編碼愉快!

拜倫

相關文章 :
  • Cajo,用Java完成分布式計算的最簡單方法
  • Hibernate映射集合性能問題
  • Java Code Geeks Andygene Web原型
  • Servlet 3.0異步處理可將服務器吞吐量提高十倍

翻譯自: https://www.javacodegeeks.com/2011/05/java-compression.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/374505.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/374505.shtml
英文地址,請注明出處:http://en.pswp.cn/news/374505.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

蘇州面對公司發布

假設您對我們這種創業型公司和我們的發展方向感興趣的話&#xff0c;我們希望通過以下10個問答進一步添加兩方的了解。我們希望看到的是您經過深思熟慮的、對公司和自己的前途負責任的謹慎回答。而不是應付公差式的輕描淡寫&#xff08;我們會依據您回答質量的高低決定是否邀請…

linux多線程_Java+Linux,深入內核源碼講解多線程之進程

之前寫了兩篇文章&#xff0c;都是針對Linux這個系統的&#xff0c;為什么?我為什么這么喜歡寫這個系統的知識&#xff0c;可能就是為了今天的內容多線程系列&#xff0c;現在多線程不是一個面試重點 啊&#xff0c;那如果你能深入系統內核回答這個知識點&#xff0c;面試官會…

594. 最長和諧子序列

和諧數組是指一個數組里元素的最大值和最小值之間的差別 正好是 1 。 現在&#xff0c;給你一個整數數組 nums &#xff0c;請你在所有可能的子序列中找到最長的和諧子序列的長度。 數組的子序列是一個由數組派生出來的序列&#xff0c;它可以通過刪除一些元素或不刪除元素、…

解決git clone報錯SSL certificate problem

Git新手一枚&#xff0c;今天進行git clone操作時發生如下問題&#xff1a;提示無效的鏈接error: SSL certificate problem: Invalid certificate chain while accessing https://githib.com/...XXXX.git fatal: HTTP request failed解決方法也很簡單&#xff0c;一條命令就搞定…

使用內存映射文件獲取巨大的矩陣

總覽 矩陣可能真的很大&#xff0c;有時甚至比一個數組中可以容納的更大。 您可以通過具有多個數組來擴展最大大小&#xff0c;但這會使堆大小確實很大且效率低下。 一種替代方法是在內存映射文件上使用包裝器。 內存映射文件的優點是它們對堆的影響很小&#xff0c;并且可以由…

ipad連接電腦_這些應用讓iPad生產力分分鐘UP

IT時報見習記者 錢奕昀用iPad辦公這件事&#xff0c;多年前網友就在討論&#xff0c;最常見的還是那句“買前生產力&#xff0c;買后愛奇藝”。很長一段時間里&#xff0c;它的生產力屬性都是弱于娛樂屬性的。其實&#xff0c;作為PC端和移動端的形態中和&#xff0c;iPad可以…

Mac OSX 快捷鍵命令行

ctrlshift 快速放大dock的圖標會暫時放大&#xff0c;而如果你開啟了dock放大CommandOptionW 將所有窗口關閉CommandW 將當前窗口關閉(可以關閉Safari標簽欄,很實用) CommandOptionM …

將JavaFX 2.0與Swing和SWT集成

JavaFX 2.0對JavaFX的改進之一是可以更輕松地與Swing和SWT進行互操作 。 一些在線資源記錄了如何完成此操作。 其中包括將JavaFX集成到Swing應用程序和SWT Interop中 。 但是&#xff0c;在有效的類級Javadoc文檔的一個很好的示例中&#xff0c;各自的JavaFX類javafx.embed.swi…

iOS-如何返回某個字符串的拼音助記碼

我也是看了網上的一個示例代碼后&#xff0c;在它的基礎上進行的修改。因為項目上會用到&#xff0c;我相信很多人的項目上也會用到。所以實現后&#xff0c;也趕緊分享出來&#xff0c;希望后來人不需要花費時間了。 提示&#xff1a;這里用到了正則表達式&#xff0c;使用了一…

wifi rssi 計算 距離_WiFi和WLAN是一樣的?真相在這里~別再傻傻分不清了

我們通常上網的時候會說連接WiFi如果注意到無線網絡的名稱就會發現手機的連接顯示是WLAN別再將WiFI和WLAN搞混了&#xff01;二者的定義WLANWLAN的全稱為 Wireless Local Area Networks,中文意思為無線局域網絡&#xff0c;是一種數據傳輸系統。它是利用射頻技術進行數據傳輸&a…

【Shell劇本練習】得出的結論是當前用戶

推斷是否當前用戶root。假設是暗示root用戶&#xff0c;假設而不是提示對于普通用戶#!/bin/bash #title: testus.sh #author: orangleliu #date: 2014-08-09 #desc: get current user, if it is root user, tell us it is super user or tell us is a common user# #Function C…

播放框架模塊:分而治之

通常情況是您開始開發應用程序并繼續滿足要求。 當您的應用程序變得更大時&#xff0c;您開始意識到將其分為不同組件的便利。 而且&#xff0c;當您開發第二個或第三個應用程序時&#xff0c;您開始認識到可以在不同應用程序之間重用的某些功能。 這是模塊化應用程序的兩個很好…

Alpha階段項目總結

1.我們的軟件要解決什么問題&#xff1f;是否定義得很清楚&#xff1f;是否對典型用戶和典型場景有清晰的描述&#xff1f; 我們的軟件是一款針對健康飲食而做的一款飲食健康軟件&#xff0c;對生活中我們經常遲到的很多事物組合都進行了詳細的注解&#xff0c;用戶可以清楚地看…

實用的it知識學習_怎樣能更快更好的學習好書法?分享一些比較實用的理論知識...

如何能更快更高效的學習書法&#xff1f;首先了解一些書法理論知識是很有必要的&#xff01;它能讓你在學習書法的過程中不至于迷茫 &#xff01;能助你更快學好書法&#xff01;一、書論在實踐中產生我們大部分人都覺得學習書法可以沒有理論&#xff0c;但不可無技法。但理論和…

九度oj-1001-Java

題目描述&#xff1a; This time, you are supposed to find AB where A and B are two matrices, and then count the number of zero rows and columns. 輸入&#xff1a; The input consists of several test cases, each starts with a pair of positive integers M and N …

字節流與字符流的區別

最近在項目中遇到一個encoding的問題&#xff0c;記錄一下。 具體而言就是&#xff0c;項目中有A/B兩個部分&#xff0c;A部分由我們負責&#xff0c;Java實現&#xff1b;B部分是UK負責的&#xff0c;使用Delphi&#xff0c;A、B在交互時發送一個http請求&#xff0c; 請求匯總…

通過MOXy實現使JAXB更加清潔

編組和解組XML時使用JAXB的主要優點是編程模型。 只需注釋幾個POJO并使用JAXB API&#xff0c;您就可以很容易地序列化為XML和從XML反序列化。 您無需擔心有關XML如何編組/解組的細節。 一切都比DOM和SAX等替代方案簡單得多。 現在&#xff0c;XML文件中的數據本質上趨于分層。…

android 上下滾動文字_計算機畢設項目004之Android系統在線小說閱讀器

計算機畢設項目004之Android系統在線小說閱讀器一. 項目名稱基于Android系統的在線小說閱讀器二. 項目簡介項目中的角色功能&#xff1a;支持翻頁動畫:仿真翻頁、覆蓋翻頁、上下滾動翻頁等翻頁效果。支持頁面定制:亮度調節、背景調節、字體大小調節支持全屏模式(含有虛擬按鍵的…

697. 數組的度

給定一個非空且只包含非負數的整數數組 nums&#xff0c;數組的 度 的定義是指數組里任一元素出現頻數的最大值。 你的任務是在 nums 中找到與 nums 擁有相同大小的度的最短連續子數組&#xff0c;返回其長度。 來源&#xff1a;力扣&#xff08;LeetCode&#xff09; 鏈接&a…

python math模塊

1.math簡介 >>> import math >>>dir(math) #這句可查看所有函數名列表 [__doc__, __name__, __package__, acos, acosh, asin, asinh, atan, atan2, atanh, ceil, copysign, cos, cosh, degrees, e, erf, erfc, exp, expm1, fabs, factorial, flo…