Question

I'm trying to create a servlet that is able to unzip a folder which contains 3 csv files and then print out the data of each csv file.

I have been trying to use ZipInputStream but it does not provide me the capability of reading/printing content of each csv.

As i'm building this web app on GAE, I'm unable to use FileOutputStream.

Are there ways to use ZipInputStream to unzip and read individual csv without the need to create a csv on GAE?

public class AdminBootStrap extends HttpServlet {

public void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
    resp.setContentType("text/plain");

    PrintWriter out = resp.getWriter();

     try {
          ServletFileUpload upload = new ServletFileUpload();
          resp.setContentType("text/plain");

          FileItemIterator iterator = upload.getItemIterator(req);
          while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream in = item.openStream();

            if (item.isFormField()) {
              out.println("Got a form field: " + item.getFieldName());
            } else {
              out.println("Got an uploaded file: " + item.getFieldName() +
                          ", name = " + item.getName());


            ZipInputStream zis = new ZipInputStream(new BufferedInputStream(in));

            ZipEntry entry;

            // Read each entry from the ZipInputStream until no
            // more entry found indicated by a null return value
            // of the getNextEntry() method.
            //
            while ((entry = zis.getNextEntry()) != null) {

                out.println("Unzipping: " + entry.getName());
                //until this point, i'm only available to print each csv name.
                //What I want to do is to print out the data inside each csv file.

            }

            }
          }
        } catch (Exception ex) {
         ex.printStackTrace();
            // throw new ServletException(ex);
        }
      }

}

Was it helpful?

Solution

ZipInputStream is an InputStream, so you can read from it as normal:

while ((entry = zis.getNextEntry()) {

    byte[] buf = new byte[1024];
    int len;
    while ((len = zis.read(buf)) > 0) {
        // here do something with data in buf
    }

   

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top