2012-06-19 5 views
2

Java에서 알고리즘을 작성하여 더 많은 폴더가 포함 된 폴더와 이미지 및 오디오 파일이 포함 된 폴더를 읽고 구조가 이렇게됩니다. : mainDir/categorySubfolder/myFile1.jpg최대 파일 크기 제한을 사용하여 java zip 아카이브를 만드는 방법

내 문제는 내가 아카이브의 크기를 16MB로 제한하고 메인 mainDir 폴더의 모든 파일을 포함하는 데 필요한만큼 많은 아카이브를 생성해야한다는 것입니다.

그물에서 몇 가지 예제를 시도했지만 Java 설명서를 읽었지만 이해할 수없고 필요에 따라 모두 넣을 수 없습니다. 누군가 이전에이 작업을 수행했거나 링크 또는 예제가 있습니까?

재귀 적 방법으로 파일 읽기를 해결했지만 zip 생성 논리를 쓸 수 없습니다.

제안이 나 더 좋은 예제가 열려 있습니다.

+0

인터넷에서 시도한 몇 가지 예는 무엇입니까? 네가 그 (것)들을 시도 할 때 무엇이 ​​일어 났는가? –

+0

http://stackoverflow.com/questions/11084823/filenotfoundeception-no-such-file-or-directory 이것은 내가 처음 수정 한 실수 였지만 이제는 2 개가 더 생겨났습니다. 첫 번째 문제는 나는 ZipEntry의 크기를 설정할 수없고 두 번째 것은 내가 파일 압축을 풀려고 할 때 '압축 방법이 지원되지 않습니다'라는 오류가 발생합니다. – androidu

+0

ZipEntry 논리 값을 설정할 수 없기 때문에 작동하지 않아 항상 하나의 아카이브 만 만듭니다. – androidu

답변

4

zip4j :-) 개선 할 수있는 많은, 여러 가지가 있습니다.

net.lingala.zip4j.core.ZipFile zipFile = new ZipFile("out.zip"); 
ZipParameters parameters = new ZipParameters(); 
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); 
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); 
zipFile.createZipFileFromFolder("path/to/source/dir", parameters, true, maximum size); 

웹 사이트에서 더 많은 예제를 찾을 수 있습니다.

1

지금까지 볼 수 있듯이 How to split a huge zip file into multiple volumes?은 지금까지 아카이브 크기를 추적하고 몇 가지 임의의 값 (최대 값보다 낮아야 함)에 도달하면 새 파일을 시작하기로 결정합니다. 따라서 16MB 제한의 경우 값을 10MB로 설정하고 도달 할 때마다 새 우편 번호를 시작할 수 있습니다. 그러나 9MB에 도달하고 다음 파일이 8MB로 줄어들면 제한보다 큰 우편 번호로 끝납니다.

ZipEntry가 만들어지기 전에 1) 크기가 있으므로 항상 0과 2) zip을 쓰지 않았기 때문에 해당 게시물에 주어진 코드가 나에게 적합하지 않은 것처럼 보였습니다. 내가 잘못했다면 알려주세요.

다음은 저에게 적합합니다. 간단히하기 위해 Wrapper에서 꺼내어 모든 것을 main (String args [])에 넣었습니다. 이 코드는 여러 부분 zip 파일을 만들 수있는 좋은 라이브러리가

import java.util.zip.*; 
import java.io.*; 



    public class ChunkedZipTwo { 

     static final long MAX_LIMIT=10 * 1000 * 1024; //10MB limit - hopefully this 


     public static void main(String[] args) throws Exception {  


      String[] files = {"file1", "file2", "file3"}; 
      int i = 0; 
      boolean needNewFile = false; 
      long overallSize = 0; 
      ZipOutputStream out = getOutputStream(i); 
      byte[] buffer = new byte[1024]; 

      for (String thisFileName: files) { 


        if (overallSize > MAX_LIMIT) { 
         out.close(); 
         i++; 
         out = getOutputStream(i); 
         overallSize=0; 
        } 

        FileInputStream in = new FileInputStream(thisFileName); 
        ZipEntry ze = new ZipEntry(thisFileName); 
        out.putNextEntry(ze); 
        int len; 
        while ((len = in.read(buffer)) > 0) { 
         out.write(buffer, 0, len); 
        } 
        out.closeEntry(); 
        in.close(); 
        overallSize+=ze.getCompressedSize(); 




      } 
      out.close();  
     } 

     public static ZipOutputStream getOutputStream(int i) throws IOException { 
      ZipOutputStream out = new ZipOutputStream(new FileOutputStream("bigfile" + i +".zip")); 
      out.setLevel(Deflater.DEFAULT_COMPRESSION); 
      return out; 
     } 
} 
+0

나는 확실히 이것을 시도 할 것입니다 :) 네 말이 맞아요. 샘플 코드에서 동일한 동작을 얻었습니다. 내 결과로 돌아갈 것이다 : D 감사합니다. – androidu

+0

감사합니다. 원하는 결과를 얻기 위해 코드에 약간의 수정을가했습니다! : D – androidu

+1

문제 없어요. 무엇을 바꾸어야 했습니까? –

1

다음 코드/클래스를 사용하여 많은 양/크기의 파일을 분할하고 압축합니다. (압축) 116

  • 전체 크기 : 29.1 GB
  • ZIP 파일 크기 제한 (각각) : 3 GB [MAX_ZIP_SIZE]
  • 난 압축 파일
    • 아래 번호에 클래스를 테스트 한
    • 전체 크기 (압축) 3
    0,123 : 7.85 GB는 ZIP 파일
  • 번호 (MAX_ZIP_SIZE로 splited)

    당신은 * 16 (MB)에 1024 * 1024 = 16777216-22 (우편 헤더 크기) = 16777194MAX_ZIP_SIZE의 값을 변경해야합니다.
    내 코드에서 MAX_ZIP_SIZE를 3GB (ZIP has limitation of 4GB on various things)로 설정하십시오.

    final long MAX_ZIP_SIZE = 3221225472L; 문자열이 함께 작동하도록 // 3기가바이트

    import java.io.FileInputStream; 
    import java.io.FileNotFoundException; 
    import java.io.FileOutputStream; 
    import java.io.IOException; 
    import java.util.zip.ZipEntry; 
    import java.util.zip.ZipOutputStream; 
    
    public class QDE_ZIP { 
    
        public static String createZIP(String directoryPath, String zipFileName, String filesToZip) { 
         try { 
          final int BUFFER = 104857600; // 100MB 
          final long MAX_ZIP_SIZE = 3221225472L; //3 GB 
          long currentSize = 0; 
          int zipSplitCount =0; 
          String files[] = filesToZip.split(","); 
          if (!directoryPath.endsWith("/")) { 
           directoryPath = directoryPath + "/"; 
          } 
          byte fileRAW[] = new byte[BUFFER]; 
          ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(directoryPath + zipFileName.toUpperCase())); 
          ZipEntry zipEntry; 
          FileInputStream entryFile; 
          for (String aFile : files) { 
           zipEntry = new ZipEntry(aFile); 
           if (currentSize >= MAX_ZIP_SIZE) 
           { 
            zipSplitCount ++; 
            //zipOut.closeEntry(); 
            zipOut.close(); 
            zipOut = new ZipOutputStream(new FileOutputStream(directoryPath + zipFileName.toLowerCase().replace(".zip", "_"+zipSplitCount+".zip").toUpperCase())); 
            currentSize = 0; 
           } 
           zipOut.putNextEntry(zipEntry); 
           entryFile = new FileInputStream(directoryPath + aFile); 
    
           int count; 
           while ((count = entryFile.read(fileRAW, 0, BUFFER)) != -1) { 
            zipOut.write(fileRAW, 0, count); 
    
            //System.out.println("number of Bytes read = " + count); 
           } 
           entryFile.close(); 
           zipOut.closeEntry(); 
           currentSize += zipEntry.getCompressedSize(); 
          } 
    
          zipOut.close(); 
          //System.out.println(directory + " -" + zipFileName + " -Number of Files = " + files.length); 
         } catch (FileNotFoundException e) { 
          return "FileNotFoundException = " + e.getMessage(); 
         } catch (IOException e) { 
          return "IOException = " + e.getMessage(); 
         } catch (Exception e) { 
          return "Exception = " + e.getMessage(); 
         } 
    
         return "1"; 
        } 
    
    } 
    

    나는 모든 예외 메시지을 돌아왔다. 이 프로젝트에 관련된 내 자신의 케이스.

  • 관련 문제