2

Copy files from one zipfile subfolder to other zipfile subfolder. version and folder are subfolders name getting from frontend.

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";
}

Getting error as follow:

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)

I'm getting an error at zipout.closeEntry(); But I can't remove this line.

john
  • 109
  • 1
  • 1
  • 7

4 Answers4

6

Resolved error by using new stream with new zipentry.

loc_ze = new ZipEntry(zEntry.getName()); 
zipout.putNextEntry(loc_ze); 
zipfile = new ZipFile(sourceFile); 
InputStream stream = zipfile.getInputStream(zEntry); 
while ((len = stream.read(b)) != -1) { 
    zipout.write(b, 0, len); 
}
kinjelom
  • 6,105
  • 3
  • 35
  • 61
john
  • 109
  • 1
  • 1
  • 7
5

You need to create a new ZEntry object to put in the ZIP output stream. You can't reuse one from a ZIP input stream: it contains stuff that the ZIP output stream wants to determine for itself. Use the appropriate constructor to copy what is really needed from the source ZIPEntry.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Can you give any sample code. I modified my code as like below but I am getting same error. zEntry = zin.getNextEntry(); ze = new ZipEntry(zEntry); zipout.putNextEntry(ze); – john Mar 31 '16 at 07:07
  • Don't construct a new ZipEntry using the ZipEntry from the zip you're reading from. Construct it like: new ZipEntry(zEntry.getName()). This was my problem. – Ring May 20 '20 at 17:07
0

Maybe the easiest solution is TrueZip (https://truezip.java.net/), see this thread Appending files to a zip file with Java

EJP is correct. For copying files inside the same archive you need two ZipEntry objects because every ZipEntry object represents one file or directory in the zip archive

See this thread Reading text files in a zip archive and this link http://www.java2s.com/Code/Java/File-Input-Output/ReadingtheContentsofaZIPFile.htm

You need a ZipFile object to which you pass the location path of your zip file

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

Then you create an enumeration of all elements of the ZipFile object

Enumeration entries = zf.entries();

As you want to copy the files in the archive you can skip this. [ To read the content of the entries use an InputStream (binary to ASCII) wrapped into a BufferedReader (reads a textfile, with format characters like EOL or EOF)BufferedReader br = new BufferedReader(new InputStreamReader(input, "UTF-8")); ]

An alternative method is ZipInputStream / ZipOutputStream

The following code reads the content of a zip archive (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();
    }
  }
}
Community
  • 1
  • 1
ralf htp
  • 9,149
  • 4
  • 22
  • 34
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();
}
kinjelom
  • 6,105
  • 3
  • 35
  • 61