| 자바 하위폴더의 압축과 해제, binaryStream을 이용한 데이터의 압축과 헤제(jazzlib를 이용) 먼저 압축을 위해 java.util.zip 패키지를 사용하였으나 한글이 깨어지는 관계로 jazzlib 패키지를 사용하였다. jazzlib는 UTF-8을 기본 문자셋으로 사용하므로 한글이 깨지지 않는 장점이 있다. http://www.jcraft.com/jzlib/index.html <-- 여기에서 jzlib-1.0.7.zip파일을 다운로드받고 라이브러리로 사용하기위해 확장자를 .jar파일로 변경하였다. 클래스패스를 잡아준후 사용하면 된다. 돌아다니는 예제소스가 부족하여 고생좀 했다. 영어를 못하는 관계로..ㅠ.ㅠ 작업한다고 이틀동안 힘들었음...ㅠ.ㅠ ZipUtil은 파일 혹은 데이터을 압축하고 해제하기 위해 만든 zip utillity이다. 주석처리가 잘 되어있으니 사용하는데는 별 문제가 없으리라 믿는다.ㅋ package common; 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; public class ZipUtil { //버퍼 사이즈를 정한다. 한번에 1024byte를 읽어온다. private static final byte[] buf = new byte[1024]; public static void createZipFile(String targetPath, String zipPath) throws Exception{ createZipFile(targetPath, zipPath, false); } public static void createZipFile(String targetPath, String zipPath, boolean isDirCre) throws Exception{ File fTargetPath = new File(targetPath); File[] files = null; //targetPath가 디렉토리일경우... if(fTargetPath.isDirectory()){ files = fTargetPath.listFiles(); } //targetPath가 파일일경우 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(); } //ZIP파일의 output Stream ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(path)); //zip파일 압축 makeZipFile(files, zipOut, ""); //stream을 닫음으로서 zip파일 생성 zipOut.close(); } public static void createZipFile(String[] targetFiles, String zipPath) throws Exception{ createZipFile(targetFiles, zipPath, false); } 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파일의 output Stream ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(path)); //zip파일 압축 makeZipFile(files, zipOut, ""); //stream을 닫음으로서 zip파일 생성 zipOut.close(); } //zip파일로 압축 private static void makeZipFile(File[] files, ZipOutputStream zipOut, String targetDir) throws Exception{ //디렉토리 내의 파일들을 읽어서 zip Entry로 추가합니다. 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); // ZIP OutputStream에 ZIP entry를 추가 // ZIP파일 내의 압축될 파일이 저장되는 경로이다...(주의!!!) zipOut.putNextEntry(new ZipEntry(targetDir+"/"+files[i].getName())); // 파일을 Zip에 쓴다. int data; while ((data = in.read(buf)) > 0) { zipOut.write(buf, 0, data); } //하나의 파일을 압축하였다. zipOut.closeEntry(); in.close(); } } public static void unZipFile(String targetZip, String completeDir) throws Exception{ unZipFile(targetZip, completeDir, false); } 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){ //zip파일의 구조와 동일하게 가기위해 로컬의 디렉토리구조를 만든다.(entry.isDirectory() 안먹음.. 젠장~!) String entryName = entry.getName(); if(entry.getName().lastIndexOf('/') > 0){ String mkDirNm = entryName.substring(0, entryName.lastIndexOf('/')); new File(completeDir+mkDirNm).mkdirs(); } //해제할 각각 파일의 output stream을 생성 FileOutputStream out = new FileOutputStream(completeDir+entry.getName()); int bytes_read; while((bytes_read=in.read(buf)) !=-1) out.write(buf, 0,bytes_read); //하나의 파일이 압축해제되었다. out.close(); } }catch(Exception e){ throw new Exception(e); }finally{ //모든파일의 압축이 해제되면 input stream을 닫는다. in.close(); } } 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(); } } 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; } public static byte[] compressToZip(String src) throws Exception { return compressToZip(src.getBytes("UTF-8")); } public static void srcToZipFile(byte[] src, String zipPath) throws Exception { byte[] retSrc = null; //압축한다. retSrc = compressToZip(src); //파일로 만든다. makeZipFile(retSrc, zipPath); } public static void srcToZipFile(String src, String zipPath) throws Exception { byte[] retSrc = null; //압축한다. retSrc = compressToZip(src.getBytes("UTF-8")); //파일로 만든다. makeZipFile(retSrc, zipPath); } public static byte[] zipFileToSrc(String zipPath) throws Exception { byte[] retSrc = null; return retSrc; } } ------------------------------ 사용법(Test.java) --------------------------------- class Test { public static void main(String[] args) { try{ //압축하기 ZipUtil.createZipFile("C:\\java\\study", "c:\\temp2\\test.zip", true); //String[] files = new String[]{"c:\\temp\\테스트.txt", "C:\\Temp\\folder\\권홍재.txt", "C:\\Temp\\folder\\할미새사촌\\두루미\\사본 - 권홍재 (6).txt"}; //ZipUtil.createZipFile(files, "c:\\temp2\\test.zip", true); //ZipUtil.createZipFile("C:\\java\\study\\test.txt", "c:\\temp2\\test.zip", true); //해제하기 ZipUtil.unZipFile("c:\\temp2\\test.zip", "c:\\temp3\\", true); //ZipUtil.unZipFile("c:\\temp2\\test.zip", "c:\\temp3\\", false); //문자열의 압축과 해제 String str = "테스트 데이터입니다."; byte[] src = str.getBytes("UTF-8"); src = ZipUtil.compressToZip(src); byte[] retSrc = ZipUtil.unZip(src); System.out.println(new String(retSrc, "UTF-8")); }catch(Exception e){ e.printStackTrace(); } } } |
오라클자바커뮤니티 핵심 실무 강좌 - 개인80% 환급
댓글 없음:
댓글 쓰기