Thursday, March 4, 2010

Display the contents of a Zip file

package com.jijo.servlet;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ZipView extends HttpServlet
{
    /**
     * Display the contents of a zip file
     */
    private static final long serialVersionUID = 1L;

    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
    {
        try
        {
            String zipFile = request.getParameter("fileNames");//specify the zip file           
            response.setContentType("text/html"); 
            PrintWriter out = response.getWriter();
            out.println("<table><tr><th>File Name</th><th>Size</th><th>Date </th><th>Compressed Size</th></tr>");
            if(zipFile != null && zipFile.trim().length()>0){
               
                //BufferedOutputStream out = null;
                ZipInputStream  in = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile)));
                ZipEntry entry;
                while((entry = in.getNextEntry()) != null)
                {
                    out.println("<tr><td>"+ entry.getName()+"</td><td>"+ entry.getSize()+"</td><td>"+ entry.getTime() +" </td><td>"+ entry.getCompressedSize() +" </td></tr>");
                    /*System.out.println(entry.getName());
                    int count;
                    byte data[] = new byte[1000];
                    out = new BufferedOutputStream(new FileOutputStream("C:/pdf/out.txt"),1000);
                    while ((count = in.read(data,0,1000)) != -1)
                    {
                        out.write(data,0,count);
                    }
                    out.flush();
                    out.close();
                    */
                }               
            }
            out.println("</table>");       
            out.flush();
            out.close();           
           
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    } 
   
    public void doGet(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException {
        doPost(request, response);
    }
   }

//Put the servlet entry in web.xml file

No comments: