hanker

JAVA - 파일 압축 본문

JAVA

JAVA - 파일 압축

hanker 2020. 8. 21. 20:52
	public static void zipDirectory(String dir, String zipfile) throws IOException,  IllegalArgumentException{
              
              //파일리스트 가져오기 위해 객체 생성
              File d = new File(dir);
              
              //디렉토리 존재유무
              if(!d.isDirectory())
                     throw new IllegalArgumentException("Not a directory : " +  dir);
              
              //해당 경로의 파일을 배열로 가져옴
              String[] entries = d.list();
              
              //파일 복사를 위한 버퍼
              byte[] buffer = new byte[4096];
              int bytesRead;
              
              //zip파일을 생성하기 위한 객체 생성
              ZipOutputStream out = new ZipOutputStream(new  FileOutputStream(zipfile));
              
              //해당경로의 파일들을 루프
              for(int i = 0 ; i < entries.length ; i++) {
                     File f = new File(d, entries[i]);
                     
                     if(f.isDirectory())
                           continue;
                     
                     //스트림으로 파일을 읽음
                     FileInputStream in = new FileInputStream(f);
                     
                     //zip파일을 만들기 위하여 out객체에 write하여 zip파일 생성
                     ZipEntry entry = new ZipEntry(f.getPath()); //make a ZipEntry
                     
                     System.out.println("압축 대상 파일 : " + entry);
                     
                     out.putNextEntry(entry);
                     while((bytesRead = in.read(buffer)) != -1) {
                           out.write(buffer, 0, bytesRead);
                     }
                     in.close();
              }
              
              out.close();
       }
       
       public static void main(String ar[]) throws Exception{
              String zipFilePath = "파일경로";
              String zipFileName = "파일경로 + 파일명";
              
              TestZip.zipDirectory(zipFilePath, zipFileName + ".zip");
       }