简体   繁体   中英

unzip a specific file in the zip file uploaded by sp using java and google app engine

I have trying to find out the solution for to unzip a particular file using java and Google app engine. I have tried using ZipInputStream but cant able to access the zip file that is uploaded in jsp. can any one help me to come out of this?

ServletFileUpload upload = new ServletFileUpload();
             resp.setContentType("text/plain");
             FileItemIterator iterator = upload.getItemIterator(req);
              while (iterator.hasNext()) {
                  FileItemStream fileItemStream = iterator.next();
                  InputStream InputStream = fileItemStream.openStream();
                  if (!fileItemStream.isFormField()) {
                      ZipInputStream zis = new ZipInputStream(new BufferedInputStream(InputStream));
                      ZipEntry entry;
                      while ((entry = zis.getNextEntry()) != null) {

                          //code to access required file in the zip file
                      }

                  } 
              }

My guess would be that ZipInputStream requires stream that is seekable. The streams returned by servlets (and networking in general) aren't seekable.

Try reading the whole stream, then wrapping it in ByteArrayInputStream :

byte[] bytes = readBytes(fileItemStream.openStream());
InputStream bufferedStream = new ByteArrayInputStream(bytes);

public static byte[] readBytes(InputStream is) throws IOException {
  ByteArrayOutputStream buffer = new ByteArrayOutputStream();

  int len;
  byte[] data = new byte[100000];
  while ((len = is.read(data, 0, data.length)) != -1) {
    buffer.write(data, 0, len);
  }

  buffer.flush();
  return buffer.toByteArray();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM