자바 압축 풀기
도구 종류:
package com.mazaiting;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GzipUtil {
/**utf-8 */
public static final String GZIP_ENCODE_UTF_8 = "UTF-8";
/**iso-8859-1 */
public static final String GZIP_ENCODE_ISO_8859_1 = "ISO-8859-1";
/**
* "utf-8"
* @param string
* @return
*/
public static byte[] compress(String string) {
return compress(string, GZIP_ENCODE_UTF_8);
}
/**
*
* @param string
* @param encoding
* @return
*/
public static byte[] compress(String string, String encoding) {
//
if (null == string || string.length() == 0) {
return null;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzipOutputStream;
try {
gzipOutputStream = new GZIPOutputStream(baos);
gzipOutputStream.write(string.getBytes(encoding));
gzipOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return baos.toByteArray();
}
/**
*
* @param bytes
* @return
*/
public static byte[] uncompress(byte[] bytes) {
if (null == bytes || bytes.length == 0) {
return null;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
GZIPInputStream unGzip;
try {
unGzip = new GZIPInputStream(bais);
byte[] buffer = new byte[256];
int n;
while ((n = unGzip.read(buffer)) >= 0) {
baos.write(buffer, 0, n);
}
} catch (Exception e) {
e.printStackTrace();
}
return baos.toByteArray();
}
/**
* "utf-8"
* @param bytes
* @return
*/
public static String uncompressToString(byte[] bytes) {
return uncompressToString(bytes, GZIP_ENCODE_UTF_8);
}
/**
*
* @param string
* @param encoding
* @return
*/
public static String uncompressToString(byte[] bytes, String encoding) {
if (null == bytes || bytes.length == 0) {
return null;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
GZIPInputStream unGzip;
try {
unGzip = new GZIPInputStream(bais);
byte[] buffer = new byte[256];
int n;
while ((n = unGzip.read(buffer)) >= 0) {
baos.write(buffer, 0, n);
}
return baos.toString(encoding);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
구체 적 인 사용:
package com.mazaiting;
public class Test {
public static void main(String[] args) {
String string = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
System.out.println(" : " + string.length());
System.out.println(" : " + GzipUtil.compress(string).length);
System.out.println(" : " + GzipUtil.uncompress(GzipUtil.compress(string)).length);
System.out.println(" : " + GzipUtil.uncompressToString(GzipUtil.compress(string)).length());
}
}
2. Zip 압축 풀기
글 에 필요 한 도구 클래스 자바 파일 옮 겨 다 니 기
/**
* Zip
* @author mazaiting
*/
public class ZipUtil {
/** --1M*/
private static final int BUFF_SIZE = 1024 * 1024;
/**
* ( )
* @param resFileList ( )
* @param zipFile
* @throws IOException
*/
public static void zipFiles(Collection resFileList, File zipFile) throws IOException {
ZipOutputStream zipOut = new ZipOutputStream(
new BufferedOutputStream(new FileOutputStream(zipFile), BUFF_SIZE));
for (File resFile : resFileList) {
zipFile(resFile, zipOut, "");
}
zipOut.close();
}
/**
* ( )
* @param resFileList ( )
* @param zipFile
* @param comment
* @throws IOException
*/
public static void zipFiles(Collection resFileList, File zipFile, String comment) throws IOException {
ZipOutputStream zipOut = new ZipOutputStream(
new BufferedOutputStream(new FileOutputStream(zipFile), BUFF_SIZE));
for (File resFile : resFileList) {
zipFile(resFile, zipOut, "");
}
zipOut.setComment(comment);
zipOut.close();
}
/**
*
* @param zipFile
* @param folderPath
* @throws IOException
* @throws ZipException
*/
public static void upZipFile(File zipFile, String folderPath) throws ZipException, IOException {
//
File desDir = new File(folderPath);
// ,
if (!desDir.exists()) {
desDir.mkdirs();
}
//
ZipFile zFile = new ZipFile(zipFile);
//
for (Enumeration> entries = zFile.entries(); entries.hasMoreElements(); ){
ZipEntry entry = (ZipEntry) entries.nextElement();
InputStream in = zFile.getInputStream(entry);
String str = folderPath + File.separator + entry.getName();
str = new String(str.getBytes("8859_1"), "GB2312");
File desFile = new File(str);
//
if (!desFile.exists()) {
File fileParentDir = desFile.getParentFile();
//
if (!fileParentDir.exists()) {
fileParentDir.mkdirs();
}
//
desFile.createNewFile();
}
OutputStream out = new FileOutputStream(desFile);
byte[] buffer = new byte[BUFF_SIZE];
int realLength;
while ((realLength = in.read(buffer)) >0) {
out.write(buffer, 0, realLength);
}
in.close();
out.close();
}
}
/**
*
* @param zipFile
* @param folderPath
* @param nameContains
* @throws ZipException
* @throws IOException IO
*/
public static ArrayList upZipSelectedFile(File zipFile, String folderPath,
String nameContains) throws ZipException, IOException {
ArrayList fileList = new ArrayList();
File desDir = new File(folderPath);
if (!desDir.exists()) {
desDir.mkdir();
}
ZipFile zf = new ZipFile(zipFile);
for (Enumeration> entries = zf.entries(); entries.hasMoreElements();) {
ZipEntry entry = ((ZipEntry)entries.nextElement());
if (entry.getName().contains(nameContains)) {
InputStream in = zf.getInputStream(entry);
String str = folderPath + File.separator + entry.getName();
str = new String(str.getBytes("8859_1"), "GB2312");
// str.getBytes("GB2312"),"8859_1"
// str.getBytes("8859_1"),"GB2312"
File desFile = new File(str);
if (!desFile.exists()) {
File fileParentDir = desFile.getParentFile();
if (!fileParentDir.exists()) {
fileParentDir.mkdirs();
}
desFile.createNewFile();
}
OutputStream out = new FileOutputStream(desFile);
byte buffer[] = new byte[BUFF_SIZE];
int realLength;
while ((realLength = in.read(buffer)) > 0) {
out.write(buffer, 0, realLength);
}
in.close();
out.close();
fileList.add(desFile);
}
}
return fileList;
}
/**
*
* @param resFile ( )
* @param zipOut
* @param rootPath
* @throws IOException
*/
private static void zipFile(File resFile, ZipOutputStream zipOut, String rootPath) throws IOException {
// 0, 0 string "/", 0 ""
String string = rootPath.trim().length() == 0 ? "" : File.separator;
//
rootPath = rootPath + string + resFile.getName();
//
rootPath = new String(rootPath.getBytes("8859_1"), "GB2312");
//
if (resFile.isDirectory()) {
//
File[] listFiles = resFile.listFiles();
for (File file : listFiles) {
zipFile(file, zipOut, rootPath);
}
} else {
byte[] buffer = new byte[BUFF_SIZE];
BufferedInputStream in = new BufferedInputStream(
new FileInputStream(resFile), BUFF_SIZE);
zipOut.putNextEntry(new ZipEntry(rootPath));
int realLength;
while ((realLength = in.read(buffer)) != -1) {
zipOut.write(buffer, 0, realLength);
}
in.close();
zipOut.flush();
zipOut.closeEntry();
}
}
/**
*
* @param zipFile
* @return
* @throws IOException
* @throws ZipException
*/
public static ArrayList getEntriesNames(File zipFile) throws ZipException, IOException {
ArrayList entryNames = new ArrayList<>();
Enumeration> entries = getEntriesEnumeration(zipFile);
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
entryNames.add(new String(
getEntryName(entry).getBytes("GB2312"), "8859_1"));
}
return entryNames;
}
/**
*
* @param entry
* @return
* @throws UnsupportedEncodingException
*/
private static String getEntryName(ZipEntry entry) throws UnsupportedEncodingException {
return new String(entry.getName().getBytes("GB2312"), "8859_1");
}
/**
*
* @param entry
* @return
* @throws UnsupportedEncodingException
*/
public static String getEntryComment(ZipEntry entry) throws UnsupportedEncodingException {
return new String(entry.getComment().getBytes("GB2312"), "8859_1");
}
/**
*
* @param zipFile
* @return
* @throws IOException
* @throws ZipException
*/
private static Enumeration> getEntriesEnumeration(File zipFile) throws ZipException, IOException {
ZipFile zf = new ZipFile(zipFile);
return zf.entries();
}
}
public class Test {
public static void main(String[] args) throws IOException {
ArrayList listFiles = DirTraversal.listFiles("E:\\web");
for (File file : listFiles) {
System.out.println(file.getAbsolutePath());
}
File zipFile = new File("E:\\web\\file.zip");
ZipUtil.zipFiles(listFiles, zipFile);
// File zipFile = new File("E:\\web\\file.zip");
// ZipUtil.zipFiles(listFiles, zipFile, "Hello");
// File zipFile = new File("E:\\web\\file.zip");
// ZipUtil.upZipFile(zipFile, "E:\\web");
}
}
3. 아파 치 커 먼 스 압축 풀기
AR, cpio, Unix dump, tar, zip, gzip, XZ, Pack 200, bzip 2, 7z, arj, lzma, snappy, DEFLATE, lz4, Brotli and Z files 형식 을 지원 합 니 다.
/**
* BZip2
* @author mazaiting
*/
public class BZip2Util {
/** */
public static final int BUFFER = 1024;
/** */
public static final String EXT = ".bz2";
/**
*
* @param data
* @return
* @throws IOException
*/
public static byte[] compress(byte[] data) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//
compress(bais, baos);
byte[] output = baos.toByteArray();
//
baos.flush();
//
baos.close();
bais.close();
return output;
}
/**
*
* @param file
* @param delete
* @throws IOException
*/
public static void compress(File file, boolean delete) throws IOException {
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(file.getPath() + EXT);
compress(fis, fos);
fos.flush();
fos.close();
fis.close();
if (delete) {
file.delete();
}
}
/**
*
* @param is
* @param os
* @throws IOException
*/
private static void compress(InputStream is, OutputStream os) throws IOException {
BZip2CompressorOutputStream bcos = new BZip2CompressorOutputStream(os);
int count;
byte data[] = new byte[BUFFER];
while((count = is.read(data, 0, BUFFER)) != -1){
bcos.write(data, 0, count);
}
bcos.finish();
bcos.flush();
bcos.close();
}
/**
*
* @param path
* @param delete
* @throws IOException
*/
public static void compress(String path, boolean delete) throws IOException{
File file = new File(path);
compress(file, delete);
}
/**
*
* @param data
* @return
* @throws IOException
*/
public static byte[] deCompress(byte[] data) throws IOException{
ByteArrayInputStream bais = new ByteArrayInputStream(data);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//
deCompress(bais, baos);
data = baos.toByteArray();
baos.flush();
baos.close();
bais.close();
return data;
}
/**
*
* @param file
* @param delete
* @throws IOException
*/
public static void deCompress(File file, boolean delete) throws IOException{
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(file.getPath().replace(EXT, ""));
deCompress(fis, fos);
fos.flush();
fos.close();
fis.close();
if (delete) {
file.delete();
}
}
/**
*
* @param is
* @param os
* @throws IOException
*/
private static void deCompress(InputStream is, OutputStream os) throws IOException {
BZip2CompressorInputStream bcis = new BZip2CompressorInputStream(is);
int count;
byte data[] = new byte[BUFFER];
while((count = bcis.read(data, 0, BUFFER)) != -1){
os.write(data, 0, count);
}
bcis.close();
}
/**
*
* @param path
* @param delete
* @throws IOException
*/
public static void deCompress(String path, boolean delete) throws IOException{
File file = new File(path);
deCompress(file, delete);
}
}
위 는 BZip 2 압축 코드 입 니 다. 다른 형식의 압축 을 풀 려 면 코드 에 있 는 BZip2Compressor InputStream 과 BZip2Compressor OutputStream 을 대응 하 는 교체 하면 됩 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.