예를 들어 Java를 사용하여 7z 파일을 압축 및 압축 해제하는 방법을 보여 줍니다.
우선 인터넷에서 7z에 대한 압축 내용이 매우 적다.
특히 자바 호출은 압축을 하는 것이 더 적다.
한 번은 스스로 완성한 압축이다.
본인이 테스트를 진행한 것은 성공적이었다.
압축된 흐름을 디스크의 압축 파일처럼 쓰십시오.
그리고 7z의 압축 소프트웨어를 사용하여 압축을 풀다.
7-zip의 개원 프로젝트 7-zip-JBinding프로젝트 주소 (sourceforge)
말할 것도 없이 7z 원본을 호출하여 압축하는 방법은 다음과 같다.
public byte[] lzmaZip(String xml) throws IOException{
BufferedInputStream inStream = new BufferedInputStream(new ByteArrayInputStream(xml.getBytes()));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
boolean eos = true;
Encoder encoder = new Encoder();
encoder.SetEndMarkerMode(eos);
encoder.WriteCoderProperties(bos);
long fileSize = xml.length();
if (eos)
fileSize = -1;
for (int i = 0; i < 8; i++)
bos.write((int)(fileSize >>> (8 * i)) & 0xFF);
encoder.Code(inStream, bos, -1, -1, null);
return bos.toByteArray() ;
}
7z 파일 압축 해제7-zip의 소스 프로젝트 7-zip-JBinding을 이용하여 외부 명령을 호출하는 것이 아니라 다양한 압축 파일을 압축합니다. (예를 들어 win에서 winrar를 호출하는 것).
java가 자체적으로 가지고 있는 압축 해제 모듈은 압축을 풀 수 있는 압축 유형에 한계가 있습니다.
코드 예제
package core;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;
import net.sf.sevenzipjbinding.ExtractOperationResult;
import net.sf.sevenzipjbinding.ISequentialOutStream;
import net.sf.sevenzipjbinding.ISevenZipInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
/** 7zbinding*/
public class UnZip {
void extractile(String filepath){
RandomAccessFile randomAccessFile = null;
ISevenZipInArchive inArchive = null;
try {
randomAccessFile = new RandomAccessFile(filepath, "r");
inArchive = SevenZip.openInArchive(null, // autodetect archive type
new RandomAccessFileInStream(randomAccessFile));
// Getting simple interface of the archive inArchive
ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
System.out.println(" Hash | Size | Filename");
System.out.println("----------+------------+---------");
for (final ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
final int[] hash = new int[] { 0 };
if (!item.isFolder()) {
ExtractOperationResult result;
final long[] sizeArray = new long[1];
result = item.extractSlow(new ISequentialOutStream() {
public int write(byte[] data) throws SevenZipException {
//Write to file
FileOutputStream fos;
try {
File file = new File(item.getPath());
//error occours below
// file.getParentFile().mkdirs();
fos = new FileOutputStream(file);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hash[0] ^= Arrays.hashCode(data); // Consume data
sizeArray[0] += data.length;
return data.length; // Return amount of consumed data
}
});
if (result == ExtractOperationResult.OK) {
System.out.println(String.format("%9X | %10s | %s", //
hash[0], sizeArray[0], item.getPath()));
} else {
System.err.println("Error extracting item: " + result);
}
}
}
} catch (Exception e) {
System.err.println("Error occurs: " + e);
e.printStackTrace();
System.exit(1);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
System.err.println("Error closing archive: " + e);
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
System.err.println("Error closing file: " + e);
}
}
}
}
}
호출할 때:
unzip=new UnZip();
unzip.extractile("a.7z");
압축 패키지의 파일을 현재 디렉터리로 자동으로 압축합니다. 설정을 변경할 수 있습니다.코드가 간단명료하다.문제가 있으면 위의sourceforge 프로젝트 주소에서discuss로 검색할 수 있습니다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.