Java - Zip 파일 형식 압축및 압축풀기(한글깨짐방지 - jazzlib 사용)
Posted 04 14, 2010 18:29, Filed under: Language/JAVA
# 한번의 광고 클릭으로, 당신을 대신해서 불우이웃을 도울 기회가 많아집니다.
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
#java에서 지원하는 ZipEntry, zipOutputStream 을 사용 하면 경로 내의 디렉토리명, 파일명에서 한글을 사용할경우 깨지는 현상이 발생.
jazzlib 라이브러리를 사용하면 한글깨짐 문제가 해결됩니다.
import net.sf.jazzlib.ZipEntry;
import net.sf.jazzlib.ZipOutputStream;
jazzlib 는 http://jazzlib.sourceforge.net 여기에서 다운로드 할수있습니다.
또는 아래에서 다운 하세요.
jar 파일 :
jazzlib.jar (828)
아래 내용 출처 :
http://cafe.naver.com/itmecca.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=1737
###################### ZipUtils.java ######################
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import net.sf.jazzlib.ZipEntry;
import net.sf.jazzlib.ZipInputStream;
import net.sf.jazzlib.ZipOutputStream;
/**
* FileName : ZipUtils.java
* Comment : # 인자값 내용
# createZipFile(압축할디렉토리위치, 저장될zip파일의 경로를 포함한파일명, 디렉토리 없을시 생성여부)
*/
public class ZipUtils {
private static final byte[] buf = new byte[1024];
/**
* Comment : 생성될 ZIP파일의 경로에 디렉토리가 없을경우 에러 발생
*/
public static void createZipFile(String targetPath, String zipPath)throws Exception{
createZipFile(targetPath, zipPath, false);
}
/**
* Comment : zip 파일을 생성.
*/
public static void createZipFile(String targetPath, String zipPath, boolean isDirCre)throws Exception{
File fTargetPath = new File(targetPath);
File[] files = null;
if(fTargetPath.isDirectory()){
files = fTargetPath.listFiles();
}else{
files = new File[1];
files[0] = fTargetPath;
}
File path = new File(zipPath);
File dir = null;
dir = new File(path.getParent());
if(isDirCre){
dir.mkdirs();
}
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(path));
// zip 파일 압축
makeZipFile(files, zipOut, "");
// stream을 닫음으로서 zip 파일 생성
zipOut.close();
}
/**
* Comment : # 일부 파일들을 배열로 설정하여 zip 파일 생성
* ex) String[] arrZip = new String[]{"C:\\aaa.txt", "C:\\bbb.txt", "C:\\ccc.txt"}
* ZipUtils.createZipFile(arrZip, "C:\\test.zip");
*/
public static void createZipFile(String[] targetFiles, String zipPath)throws Exception{
createZipFile(targetFiles, zipPath, false);
}
/**
* Comment : # 일부 파일들을 배열로 설정하여 zip 파일 생성 (디렉토리 생성여부 선택)
*/
public static void createZipFile(String[] targetFiles, String zipPath, boolean isDirCre)throws Exception{
File[] files = new File[targetFiles.length];
for(int i = 0; i < files.length; i++){
files[i] = new File(targetFiles[i]);
}
File path = new File(zipPath);
File dir = null;
dir = new File(path.getParent());
if(isDirCre){
// 디렉토리가 없을경우 생성
dir.mkdirs();
}
// zip 파일의 outputStream
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(path));
// zip 파일 압축
makeZipFile(files, zipOut, "");
// stream을 닫음으로서 zip 파일 생성
zipOut.close();
}
/**
* Comment : zip 파일의 압축을 해제
*/
public static void unZipFile(String targetZip, String completeDir)throws Exception{
unZipFile(targetZip, completeDir, false);
}
/**
* Comment :
*/
public static void unZipFile(String targetZip, String completeDir, boolean isDirCre)throws Exception{
ZipInputStream in = null;
try{
File fCompleteDir = null;
fCompleteDir = new File(completeDir);
if(isDirCre){
// 디렉토리가 없을경우 생성
fCompleteDir.mkdirs();
}
// zip 파일의 input stream을 읽어들임
in = new ZipInputStream(new FileInputStream(targetZip));
ZipEntry entry = null;
// input stream내의 압축된 파일들을 하나씩 읽어들임.
while((entry = in.getNextEntry()) != null){
System.out.println("entry : " + entry);
// zip 파일의 구조와 동일하게 가기위해 로컬의 디렉토리 구조를 만듬.
String entryName = entry.getName();
if(entry.getName().lastIndexOf("/") > 0){
String mkDirNm = entryName.substring(0, entryName.lastIndexOf("/"));
System.out.println("mkDirNm : " + mkDirNm);
new File(completeDir + mkDirNm).mkdirs();
}
// 해제할 각각 파일의 output stream을 생성
FileOutputStream out = new FileOutputStream(completeDir + entry.getName());
int bytes_read;
while((bytes_read = in.read(buf)) != -1){
System.out.println("bytes_read : " + bytes_read);
out.write(buf, 0, bytes_read);
}
// 하나의 파일이 압축해제됨
out.close();
}
}catch(Exception e){
throw new Exception(e);
}finally{
// 모든 파일의 압축이 해제되면 input stream을 닫는다.
in.close();
}
}
// byte 배열을 받아서 압축된 byte배열을 리턴
public static byte[] compressToZip(byte[] src)throws Exception{
byte[] retSrc = null;
ByteArrayOutputStream baos = null;
try{
// zip 파일의 output Stream
ByteArrayInputStream bais = new ByteArrayInputStream(src);
baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos) ;
zos.putNextEntry(new ZipEntry("temp.tmp"));
int bytes_read = 0;
// 전달받은 src를 압축하여 파일에 씀
while((bytes_read = bais.read(buf)) != -1){
zos.write(buf, 0, bytes_read);
}
bais.close();
zos.close();
// 스트림을 닫은후 byte배열을 얻어옴
retSrc = baos.toByteArray();
}catch(Exception e){
throw new Exception(e);
}finally{
baos.close();
}
return retSrc;
}
// 압축된 byte 배열을 받아서 zipPath위치에 zip 파일을 생성한다.
private static void makeZipFile(byte[] src, String zipPath)throws Exception{
FileOutputStream fos = null;
ByteArrayInputStream bais = null;
try{
fos = new FileOutputStream(zipPath);
bais = new ByteArrayInputStream(src);
int bytes_read = 0;
while((bytes_read = bais.read(buf)) != -1){
fos.write(buf, 0, bytes_read);
}
}catch(Exception e){
throw new Exception(e);
}finally{
fos.close();
bais.close();
}
}
// 압축된 byte 배열의 압축을 해제하여 byte배열로 리턴
public static byte[] unZip(byte[] src)throws Exception{
byte[] retSrc = null;
ByteArrayOutputStream baos = null;
ZipInputStream zis = null;
int bytes_read = 0;
try{
zis = new ZipInputStream(new ByteArrayInputStream(src));
baos = new ByteArrayOutputStream();
zis.getNextEntry(); // entry는 하나밖에 없음을 보장
while((bytes_read = zis.read(buf)) != -1){
baos.write(buf, 0, bytes_read);
}
retSrc = baos.toByteArray();
}catch(Exception e){
throw new Exception(e);
}finally{
baos.close();
zis.close();
}
return retSrc;
}
// 문자열을 압축하여 byte배열로 리턴(UTF-8)
public static byte[] compressToZip(String src)throws Exception{
return compressToZip(src.getBytes("UTF-8"));
}
// byte배열을 압축하여 zip 파일로 생성
public static void srcToZipFile(byte[] src, String zipPath)throws Exception{
byte[] retSrc = null;
// 압축
retSrc = compressToZip(src);
// 파일로 만듬
makeZipFile(retSrc, zipPath);
}
// byte 배열을 압축하여 zip 파일로 생성
public static void srcToZipFile(String src, String zipPath)throws Exception{
byte[] retSrc = null;
// 압축
retSrc = compressToZip(src.getBytes("UTF-8"));
// 파일로 만듬
makeZipFile(retSrc, zipPath);
}
// 압축된 zip파일을 해제후 byte배열로 리턴
public static byte[] zipFileToSrc(String zipPath)throws Exception{
byte[] retSrc = null;
return retSrc;
}
public static void makeZipFile(File[] files, ZipOutputStream zipOut, String targetDir) throws Exception{
for(int i = 0; i < files.length; i++){
File compPath = new File(files[i].getPath());
if(compPath.isDirectory()){
File[] subFiles = compPath.listFiles();
makeZipFile(subFiles, zipOut, targetDir+compPath.getName()+"/");
continue;
}
FileInputStream in = new FileInputStream(compPath);
zipOut.putNextEntry(new ZipEntry(targetDir+"/"+files[i].getName()));
int data;
while((data = in.read(buf)) > 0){
zipOut.write(buf, 0, data);
}
zipOut.closeEntry();
in.close();
}
}
public static void main(String[] arr) throws Exception{
// 압축하기
try {
ZipUtils.createZipFile("D:\\02.TEMP\\backup2", "D:\\02.TEMP\\AAAA\\backup2_한글지원2.zip", true);
//ZipUtils.unZipFile("D:\\02.TEMP\\backup2_aa.zip", "D:\\02.TEMP\\mkDirNm\\", true);
/*
// 문자열의 압축과 해제
String str = "테스트333 데이터입니다.";
byte[] src = str.getBytes("UTF-8");
src = ZipUtils.compressToZip(src);
byte[] retSrc = ZipUtils.unZip(src);
System.out.println(new String(retSrc, "UTF-8"));
*/
} catch (Exception e) {
throw new Exception(e);
}
}
}
import java.util.zip.ZipOutputStream;
#java에서 지원하는 ZipEntry, zipOutputStream 을 사용 하면 경로 내의 디렉토리명, 파일명에서 한글을 사용할경우 깨지는 현상이 발생.
jazzlib 라이브러리를 사용하면 한글깨짐 문제가 해결됩니다.
import net.sf.jazzlib.ZipEntry;
import net.sf.jazzlib.ZipOutputStream;
jazzlib 는 http://jazzlib.sourceforge.net 여기에서 다운로드 할수있습니다.
또는 아래에서 다운 하세요.
jar 파일 :
jazzlib.jar (828)아래 내용 출처 :
http://cafe.naver.com/itmecca.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=1737
###################### ZipUtils.java ######################
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import net.sf.jazzlib.ZipEntry;
import net.sf.jazzlib.ZipInputStream;
import net.sf.jazzlib.ZipOutputStream;
/**
* FileName : ZipUtils.java
* Comment : # 인자값 내용
# createZipFile(압축할디렉토리위치, 저장될zip파일의 경로를 포함한파일명, 디렉토리 없을시 생성여부)
*/
public class ZipUtils {
private static final byte[] buf = new byte[1024];
/**
* Comment : 생성될 ZIP파일의 경로에 디렉토리가 없을경우 에러 발생
*/
public static void createZipFile(String targetPath, String zipPath)throws Exception{
createZipFile(targetPath, zipPath, false);
}
/**
* Comment : zip 파일을 생성.
*/
public static void createZipFile(String targetPath, String zipPath, boolean isDirCre)throws Exception{
File fTargetPath = new File(targetPath);
File[] files = null;
if(fTargetPath.isDirectory()){
files = fTargetPath.listFiles();
}else{
files = new File[1];
files[0] = fTargetPath;
}
File path = new File(zipPath);
File dir = null;
dir = new File(path.getParent());
if(isDirCre){
dir.mkdirs();
}
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(path));
// zip 파일 압축
makeZipFile(files, zipOut, "");
// stream을 닫음으로서 zip 파일 생성
zipOut.close();
}
/**
* Comment : # 일부 파일들을 배열로 설정하여 zip 파일 생성
* ex) String[] arrZip = new String[]{"C:\\aaa.txt", "C:\\bbb.txt", "C:\\ccc.txt"}
* ZipUtils.createZipFile(arrZip, "C:\\test.zip");
*/
public static void createZipFile(String[] targetFiles, String zipPath)throws Exception{
createZipFile(targetFiles, zipPath, false);
}
/**
* Comment : # 일부 파일들을 배열로 설정하여 zip 파일 생성 (디렉토리 생성여부 선택)
*/
public static void createZipFile(String[] targetFiles, String zipPath, boolean isDirCre)throws Exception{
File[] files = new File[targetFiles.length];
for(int i = 0; i < files.length; i++){
files[i] = new File(targetFiles[i]);
}
File path = new File(zipPath);
File dir = null;
dir = new File(path.getParent());
if(isDirCre){
// 디렉토리가 없을경우 생성
dir.mkdirs();
}
// zip 파일의 outputStream
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(path));
// zip 파일 압축
makeZipFile(files, zipOut, "");
// stream을 닫음으로서 zip 파일 생성
zipOut.close();
}
/**
* Comment : zip 파일의 압축을 해제
*/
public static void unZipFile(String targetZip, String completeDir)throws Exception{
unZipFile(targetZip, completeDir, false);
}
/**
* Comment :
*/
public static void unZipFile(String targetZip, String completeDir, boolean isDirCre)throws Exception{
ZipInputStream in = null;
try{
File fCompleteDir = null;
fCompleteDir = new File(completeDir);
if(isDirCre){
// 디렉토리가 없을경우 생성
fCompleteDir.mkdirs();
}
// zip 파일의 input stream을 읽어들임
in = new ZipInputStream(new FileInputStream(targetZip));
ZipEntry entry = null;
// input stream내의 압축된 파일들을 하나씩 읽어들임.
while((entry = in.getNextEntry()) != null){
System.out.println("entry : " + entry);
// zip 파일의 구조와 동일하게 가기위해 로컬의 디렉토리 구조를 만듬.
String entryName = entry.getName();
if(entry.getName().lastIndexOf("/") > 0){
String mkDirNm = entryName.substring(0, entryName.lastIndexOf("/"));
System.out.println("mkDirNm : " + mkDirNm);
new File(completeDir + mkDirNm).mkdirs();
}
// 해제할 각각 파일의 output stream을 생성
FileOutputStream out = new FileOutputStream(completeDir + entry.getName());
int bytes_read;
while((bytes_read = in.read(buf)) != -1){
System.out.println("bytes_read : " + bytes_read);
out.write(buf, 0, bytes_read);
}
// 하나의 파일이 압축해제됨
out.close();
}
}catch(Exception e){
throw new Exception(e);
}finally{
// 모든 파일의 압축이 해제되면 input stream을 닫는다.
in.close();
}
}
// byte 배열을 받아서 압축된 byte배열을 리턴
public static byte[] compressToZip(byte[] src)throws Exception{
byte[] retSrc = null;
ByteArrayOutputStream baos = null;
try{
// zip 파일의 output Stream
ByteArrayInputStream bais = new ByteArrayInputStream(src);
baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos) ;
zos.putNextEntry(new ZipEntry("temp.tmp"));
int bytes_read = 0;
// 전달받은 src를 압축하여 파일에 씀
while((bytes_read = bais.read(buf)) != -1){
zos.write(buf, 0, bytes_read);
}
bais.close();
zos.close();
// 스트림을 닫은후 byte배열을 얻어옴
retSrc = baos.toByteArray();
}catch(Exception e){
throw new Exception(e);
}finally{
baos.close();
}
return retSrc;
}
// 압축된 byte 배열을 받아서 zipPath위치에 zip 파일을 생성한다.
private static void makeZipFile(byte[] src, String zipPath)throws Exception{
FileOutputStream fos = null;
ByteArrayInputStream bais = null;
try{
fos = new FileOutputStream(zipPath);
bais = new ByteArrayInputStream(src);
int bytes_read = 0;
while((bytes_read = bais.read(buf)) != -1){
fos.write(buf, 0, bytes_read);
}
}catch(Exception e){
throw new Exception(e);
}finally{
fos.close();
bais.close();
}
}
// 압축된 byte 배열의 압축을 해제하여 byte배열로 리턴
public static byte[] unZip(byte[] src)throws Exception{
byte[] retSrc = null;
ByteArrayOutputStream baos = null;
ZipInputStream zis = null;
int bytes_read = 0;
try{
zis = new ZipInputStream(new ByteArrayInputStream(src));
baos = new ByteArrayOutputStream();
zis.getNextEntry(); // entry는 하나밖에 없음을 보장
while((bytes_read = zis.read(buf)) != -1){
baos.write(buf, 0, bytes_read);
}
retSrc = baos.toByteArray();
}catch(Exception e){
throw new Exception(e);
}finally{
baos.close();
zis.close();
}
return retSrc;
}
// 문자열을 압축하여 byte배열로 리턴(UTF-8)
public static byte[] compressToZip(String src)throws Exception{
return compressToZip(src.getBytes("UTF-8"));
}
// byte배열을 압축하여 zip 파일로 생성
public static void srcToZipFile(byte[] src, String zipPath)throws Exception{
byte[] retSrc = null;
// 압축
retSrc = compressToZip(src);
// 파일로 만듬
makeZipFile(retSrc, zipPath);
}
// byte 배열을 압축하여 zip 파일로 생성
public static void srcToZipFile(String src, String zipPath)throws Exception{
byte[] retSrc = null;
// 압축
retSrc = compressToZip(src.getBytes("UTF-8"));
// 파일로 만듬
makeZipFile(retSrc, zipPath);
}
// 압축된 zip파일을 해제후 byte배열로 리턴
public static byte[] zipFileToSrc(String zipPath)throws Exception{
byte[] retSrc = null;
return retSrc;
}
public static void makeZipFile(File[] files, ZipOutputStream zipOut, String targetDir) throws Exception{
for(int i = 0; i < files.length; i++){
File compPath = new File(files[i].getPath());
if(compPath.isDirectory()){
File[] subFiles = compPath.listFiles();
makeZipFile(subFiles, zipOut, targetDir+compPath.getName()+"/");
continue;
}
FileInputStream in = new FileInputStream(compPath);
zipOut.putNextEntry(new ZipEntry(targetDir+"/"+files[i].getName()));
int data;
while((data = in.read(buf)) > 0){
zipOut.write(buf, 0, data);
}
zipOut.closeEntry();
in.close();
}
}
public static void main(String[] arr) throws Exception{
// 압축하기
try {
ZipUtils.createZipFile("D:\\02.TEMP\\backup2", "D:\\02.TEMP\\AAAA\\backup2_한글지원2.zip", true);
//ZipUtils.unZipFile("D:\\02.TEMP\\backup2_aa.zip", "D:\\02.TEMP\\mkDirNm\\", true);
/*
// 문자열의 압축과 해제
String str = "테스트333 데이터입니다.";
byte[] src = str.getBytes("UTF-8");
src = ZipUtils.compressToZip(src);
byte[] retSrc = ZipUtils.unZip(src);
System.out.println(new String(retSrc, "UTF-8"));
*/
} catch (Exception e) {
throw new Exception(e);
}
}
}
"Language / JAVA" 분류의 다른 글
| Java - Class 버전 확인 (0) | 2012/01/19 |
| Java - SimpleFormController - 조건 값에 따른 showForm 페이지 이동 (0) | 2011/11/30 |
| Java - getProperties 사용하여 현재 시스템의 정보를 추출 (0) | 2011/08/07 |
| Java - Jfreechart 패키지 이용 차트만들기 (0) | 2011/01/05 |
| Java - JfreeChart 사용시 한글깨짐(jar 파일 font 수정) (0) | 2011/01/04 |
| Java - compile및 jar 파일 생성 (0) | 2010/04/14 |
| Java - BigDecimal의 필요성 (0) | 2009/10/31 |
| Java - Date, GregorianCalendar, 날자 연산 더하기, 빼기 (0) | 2009/08/17 |
| Java - Commons Net의 FTPClient 사용하여 FTP 접속및 파일 컨트롤 (0) | 2009/08/05 |
| Java - 특수문자 제어 Util (0) | 2009/07/17 |
# 한번의 광고 클릭으로, 당신을 대신해서 불우이웃을 도울 기회가 많아집니다.
Response :
1 Trackback
,
8 Comments
Trackback URL : http://develop.sunshiny.co.kr/trackback/427
-
파일 압축
Tracked from Like RadioHead 11 8, 2010 19:07 Delete원문 출처 : http://develop.sunshiny.co.kr/trackback/427 Java - Zip 파일 형식 압축및 압축풀기(한글깨짐방지 - jazzlib 사용) Posted 2010/04/14 18:29, Filed under: Language/JAVA import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; #java에서 지원하는 ZipEntry, zipOutputS..
-
잘보았습니다~ 퍼가두될까용?? ^^
-
에구.
댓글 남기신걸 이제야 봤네요^^
네~ 당연히 괜찮죠.
저도 다른분이 정리해놓은거 가져온거 거든요.^^;
글 남겨주셔서 고맙습니다^^
-
-
감사합니다
-
네~
글 남겨 주셔서 고맙습니다^^
-
-
좋은 자료 감사합니다
담아갑니다^^-
네 고맙습니다^^
-
-
좋은글이라 담아갑니다.~ ^^ 출처도 남겼습니다. 감사해요.
-
네~
답글 고맙습니다^^
-