2016-03-29 83 views
1

將文件從一個zipfile子文件夾複製到其他zipfile子文件夾。 versionfolder是從前端獲取的子文件夾名稱。java.util.zip.ZipException:無效輸入壓縮大小(預計449但得到455字節)

public String restore(String jobId, String version, String folder) { 
    String fileName = String.valueOf(jobId) + ".zip"; 
    String versions[] = version.replaceAll("'", "") 
     .replace("[", "") 
     .replace("]", "") 
     .split(","); 
    String folders[] = folder.replaceAll("'", "").replace("[", "").replace("]", "").split(","); 
    ArrayList<String> listofVersion, listofFolder = new ArrayList<>(); 

    File destinationFile = new File(env.getProperty("file.path") + fileName); 
    File sourceFile = new File(env.getProperty("file.arcivePath") + fileName); 

    FileInputStream in; 
    FileOutputStream out; 
    ZipInputStream zin; 
    ZipOutputStream zipout; 
    int BUFFER = (int) sourceFile.length(); 

    if (!destinationFile.exists()) { 
     try { 
      out = new FileOutputStream(destinationFile); 
      zipout = new ZipOutputStream(out); //I get the "out" object from the servlet which tells the content type and and final zip file location. 
      ZipEntry zEntry, ze; 
      in = new FileInputStream(sourceFile); 
      zin = new ZipInputStream(in); 
      while ((zEntry = zin.getNextEntry()) != null) { 
       System.out.println(zEntry); 
       String entry = zEntry.getName(); 
       String entryList[] = entry.split("/"); 
       if (zEntry.isDirectory() && (entryList.length <= 1)) { 
        zipout.putNextEntry(zEntry); 
       } else { 
        if (entryList.length >= 2) { 
         listofVersion = listVersionRestore(fileName); 
         for (int j = 0; j < versions.length; j++) { 
          for (int i = 0; i < listofVersion.size(); i++) { 
           if (listofVersion.get(i).equals(versions[j])) { 
            if ((entryList.length == 2) && entryList[1].equals(versions[j])) { 
             zipout.putNextEntry(zEntry); 
            } 
            if (entryList.length >= 3) { 
             listofFolder = listFolderRestore(fileName, versions[j]); 
             for (int l = 0; l < folders.length; l++) { 
              for (int k = 0; k < listofFolder.size(); k++) { 
               if (listofFolder.get(k).equals(folders[l])) { 
                if ((entryList.length == 3) && entryList[1].equals(versions[j]) && entryList[2].equals(folders[l])) { 
                 zipout.putNextEntry(zEntry); 
                } 

                if ((entryList.length == 4) && entryList[1].equals(versions[j]) && entryList[2].equals(folders[l])) { 
                 zipout.putNextEntry(zEntry); 
                 byte[] buffer = new byte[BUFFER]; 
                 int len = 0; 
                 while ((len = zin.read(buffer)) != -1) { 
                  zipout.write(buffer, 0, len); 
                 } 

                 zipout.closeEntry(); 
                 in.close(); 
                } 

               } 
              } 
             } 
            } 
           } 
          } 
         } 
        } 
       } 
      } 
      zipout.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      return "Error"; 
     } 
    } else { 
     return "Already Exists"; 
    } 
    return "RestoredSuccessfully"; 
} 

收到錯誤如下:

java.util.zip.ZipException: invalid entry compressed size (expected 449 but got 455 bytes) 
at java.util.zip.ZipOutputStream.closeEntry(Unknown Source) 
at prj.iopo.filesystem.FileSystemHandler.restore(FileSystemHandler.java:148) 
at prj.iopo.filesystem.FileSystemHandler$$FastClassBySpringCGLIB$$f51baf3f.invoke(<generated>) 
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) 
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720) 
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) 
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) 
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) 
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) 
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) 
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655) 
at prj.iopo.filesystem.FileSystemHandler$$EnhancerBySpringCGLIB$$6d76d700.restore(<generated>) 
at prj.iopo.controller.JobController.restore(JobController.java:99) 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 
at java.lang.reflect.Method.invoke(Unknown Source) 
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222) 
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) 
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) 
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814) 
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737) 
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) 
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) 
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) 
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969) 
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860) 
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) 
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845) 
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) 
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) 
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) 
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) 
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) 
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) 
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:316) 
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126) 
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) 
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) 
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) 
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) 
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:122)89765042/1/2l/FS-restore.txt 
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) 
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) 
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) 
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169) 
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) 
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:48) 
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) 
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:213) 
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) 
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120) 
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) 
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) 
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) 
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91) 
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) 
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53) 
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) 
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213) 
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176) 
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) 
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) 
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) 
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) 
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) 
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) 
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) 
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87) 
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) 
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) 
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) 
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) 
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) 
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121) 
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) 
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) 
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212) 
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) 
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) 
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141) 
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) 
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) 
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521) 
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096) 
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674) 
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500) 
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) 
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) 
at java.lang.Thread.run(Unknown Source) 

我得到一個錯誤的zipout.closeEntry(); 但我不能刪除此行。

回答

1

您需要創建一個新的ZEntry對象來放入ZIP輸出流。您不能重複使用ZIP輸入流中的一個:它包含ZIP輸出流想要爲其自身確定的內容。使用適當的構造函數從源碼ZIPEntry複製真正需要的內容。

+0

你能不能給任何代碼示例。我修改我的代碼,如下所示,但我得到相同的錯誤。 zEntry = zin.getNextEntry(); ze =新的ZipEntry(zEntry); zipout.putNextEntry(ZE); – john

0

也許最簡單的解決方法是TrueZiphttps://truezip.java.net/),看到這個線程Appending files to a zip file with Java

EJP是正確的。對於複製相同的檔案中的文件,你需要兩個ZipEntry的對象,因爲每個ZipEntry對象代表於zip存檔

一個文件或目錄中看到這個線程Reading text files in a zip archive而這個鏈接http://www.java2s.com/Code/Java/File-Input-Output/ReadingtheContentsofaZIPFile.htm

你需要一個ZipFile對象,你傳遞您的zip文件的位置路徑

ZipFile zf = new ZipFile("/<path>/yourZip.zip");

然後創建zip文件對象的所有元素的枚舉

Enumeration entries = zf.entries();

由於您要複製檔案中的文件,您可以跳過此操作。 [要讀取的條目的內容使用的InputStream包裹成一個BufferedReader(二進制到ASCII)(讀取文本文件,用格式的字符,如EOL或EOF)BufferedReader br = new BufferedReader(new InputStreamReader(input, "UTF-8"));]

一種替代方法是ZipInputStream/ZipOutputStream

下面的代碼讀取一個zip壓縮文件的內容(http://www.java2s.com/Code/Java/File-Input-Output/ReadingtheContentsofaZIPFile.htm):

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.util.Enumeration; 
import java.util.zip.ZipEntry; 
import java.util.zip.ZipFile; 

public class ReadZip { 
    public static void main(String args[]) { 
    try { 
     ZipFile zf = new ZipFile("ReadZip.zip"); 
     Enumeration entries = zf.entries(); 

     BufferedReader input = new BufferedReader(new InputStreamReader(
      System.in)); 
     while (entries.hasMoreElements()) { 
     ZipEntry ze = (ZipEntry) entries.nextElement(); 
     System.out.println("Read " + ze.getName() + "?"); 
     String inputLine = input.readLine(); 
     if (inputLine.equalsIgnoreCase("yes")) { 
      long size = ze.getSize(); 
      if (size > 0) { 
      System.out.println("Length is " + size); 
      BufferedReader br = new BufferedReader(
       new InputStreamReader(zf.getInputStream(ze))); 
      String line; 
      while ((line = br.readLine()) != null) { 
       System.out.println(line); 
      } 
      br.close(); 
      } 
     } 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    } 
} 
3

由我們解決錯誤用新的zipentry新的流。

​​
0
static copyZip() throws IOException { 
    try (final ZipInputStream zis = new ZipInputStream(...); 
     final ZipOutputStream zos = new ZipOutputStream(...) 
    ) { 
     copyZipContent(zis, zos); 
    } 
} 

static void copyZipContent(final ZipInputStream zis, final ZipOutputStream zos) throws IOException { 
    ZipEntry zisEntry; 
    while ((zisEntry = zis.getNextEntry()) != null) { 
     ZipEntry zosEntry = new ZipEntry(zisEntry.getName()); 
     zosEntry.setComment(zisEntry.getComment()); 
     zosEntry.setExtra(zisEntry.getExtra()); 
     zos.putNextEntry(zosEntry); 
     IOUtils.copy(zis, zos); 
     zos.closeEntry(); 
    } 
    zos.finish(); 
} 
相關問題