Solved

Unzipping A File

Posted on 2004-10-25
212 Views
Last Modified: 2013-12-24
I've used the script that everyone seems to be pointing to (see below). It works great... if the files are small.  If I get a larger file (it won't even take a 1 meg file), I get an error.  See the code below and the error.  

Does anyone have any suggestions as to other options to implement that are proven? Thanks! I'm on a tight deadline for this..

error:
Object Instantiation Exception.  
An exception occurred when instantiating a java object. The cause of this exception was that: .  
 


code:
--------------------
<cfscript>

   function unzipFile(zipFilePath, outputPath) {
     
       var zipFile = ""; // ZipFile
       var entries = ""; // Enumeration of ZipEntry
       var entry = ""; // ZipEntry
       var fil = ""; //File
       var filOutStream = "";
       var bufOutStream = "";
       var nm = "";
       var pth = "";
       var lenPth = "";
 
       zipFile = createObject("java", "java.util.zip.ZipFile");
       zipFile.init(zipFilePath);
       
       entries = zipFile.entries();
 
       while(entries.hasMoreElements()) {
           entry = entries.nextElement();
 
           if(NOT entry.isDirectory()) {
               nm = entry.getName();
               
               lenPth = len(nm) - len(getFileFromPath(nm));
   
               if (lenPth) {
                   pth = outputPath & left(nm, lenPth);
                } else {
                   pth = outputPath;
                }
   
               if (NOT directoryExists(pth)) {
                   fil = createObject("java", "java.io.File");
                   fil.init(pth);
                   fil.mkdirs();
                }
   
               filOutStream = createObject(
                  "java",
                  "java.io.FileOutputStream");
   
               filOutStream.init(outputPath & nm);
               
               bufOutStream = createObject(
                  "java",
                  "java.io.BufferedOutputStream");
   
               bufOutStream.init(filOutStream);
   
               copyInputStream(
                  zipFile.getInputStream(entry),
                  bufOutStream);
            }
        }
 
       zipFile.close();
    }

   function copyInputStream(inStream, outStream) {
     
       var buffer = repeatString(" ",1024).getBytes();
       var l = inStream.read(buffer);
 
       while(l GTE 0) {
           outStream.write(buffer, 0, l);
           l = inStream.read(buffer);
        }
       inStream.close();
       outStream.close();
    }

</cfscript>

<cfset unzipFile(expandPath("test.zip"), expandPath("target\"))>
0
Question by:mailershaven
    4 Comments
     
    LVL 8

    Expert Comment

    by:sigmacon
    WOW. I have done Java inline in CF before, but this is scary. I can only suggest an improvement, but I doubt that it will help much (or even work). Change the buffer implementation like this

    var buffer = repeatString(" ", 102400).getBytes();

    function copyInputStream(inStream, outStream) {
           var l = inStream.read(buffer);
     
           while(l GTE 0) {
               outStream.write(buffer, 0, l);
               l = inStream.read(buffer);
            }
           inStream.close();
           outStream.close();
        }


    I have implemented a high-performance Java-based tool for unzipping and creating huge archives. But it is for sale and I don't know what policies EE has about posting such links. I highly suggest you look around what's available and spend the few dollars others charge for this stuff.
    0
     

    Author Comment

    by:mailershaven
    Yeah, that didn't help.

    I don't care if I have to buy it, I just want something that works and works consistantly! I've done a lot of searching and haven't found anything yet.  I'm asking you to point me to places even if they require payment.

    Thank you!
    0
     
    LVL 8

    Accepted Solution

    by:
    http://www.cfxtras.com has several tools for dealing with ZIP files. One is from our heavenly master Ben Forta, and then there is another one that I prefer ... if you know what I mean ;-)
    0
     
    LVL 8

    Expert Comment

    by:sigmacon
    IF YOU HAVE the java SDK (http://java.sun.com/j2se/1.4.2/download.html - not the JRE!) installed and are not afraid to get your hands dirty with some java compilation, you can try this. All the following instructions assume Windows. First, make sure your java compiler can be executed.

    Open command prompt and type: javac

    If you get something like 'command not found' make sure that the java SDK installation bin directory is in your path (usually something like C:\j2sdk-1.4.2_32\bin).

    Then copy the following code to a text file and save as SimpleCFUnzip.java (spelling matters, or not):

    ---- Start of Java Code -----

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

    public class SimpleCFUnzip {
          public boolean unzipFile(String zipFilePath, String outputPath) throws Exception {
                ZipFile zipFile = new ZipFile(zipFilePath);
                Enumeration entries = zipFile.entries();
                
                ZipEntry entry = null;
                String nm = null; // name of the file
                File f = null; // folder represented by the path
                BufferedOutputStream out = null;
                if (!(outputPath.endsWith("/") || outputPath.endsWith("/"))) {
                      outputPath += "/";
                }
                
                while(entries.hasMoreElements()) {
                      entry = (ZipEntry)entries.nextElement();
                      
                      if(!entry.isDirectory()) {
                            nm = outputPath + entry.getName();
                            f = new File(nm);
                            out = new BufferedOutputStream(new FileOutputStream(f));
                            copyInputStream(zipFile.getInputStream(entry), out);
                      }
                }
                zipFile.close();
                return true;
          }
          private void copyInputStream(InputStream inStream, OutputStream outStream) throws Exception {
                byte[] buf = new byte[102400];
                int len;
                try {
                      while((len = inStream.read(buf)) > -1) {
                            outStream.write(buf, 0, len);
                      }
                } catch (Exception e) {
                      inStream.close();
                      outStream.close();
                      throw e;
                } finally {
                      inStream.close();
                      outStream.close();
                }
          }
          
    }

    ---- End of Java Code -----

    Then open a command prompt in the folder where you saved this file and type:

    javac -O SimpleCFUnzip.java

    Now there should also be a file SimpleCFUnzip.class - copy this file in the \wwwroot\WEB-INF\lib folder of your ColdFusion installation (usually something like C:\CFusionMX\wwwroot\WEB-INF\lib) and restart ColdFusion.

    To use this for unzipping files, this is the CF code:

    <cfscript>

    unzip = createObject('java', 'SimpleCFUnzip');
    unzip.unzipFile( unzipFile , unzipTargetFolder );

    </cfscript>

    I tested with a 30MB large zip file and it worked fine. Here are the restrictions for this very simple approach:

    1) Only handle files in the zip archive that have no folder or path information, just files in the 'root'
    2) Performs hardly any error checking whatsoever. It's a good idea to wrap calls to this in a <cftry>-<cfcatch> block and deal with it appropriately
    3) It does not create any folders, like the CF version above. You are responsible for all folders to exist

    if you want to unzip more than one file, please recreate a new object; that is, do

    unzip = createObject('java', 'SimpleCFUnzip');
    unzip.unzipFile( unzipFile , unzipTargetFolder );

    for each unzip call. In my experience, this is better for memory behavior in the long run.
    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone. Privacy Policy Terms of Use

    Featured Post

    Course: JavaScript Coding - Massive 12-Part Bundle

    Regardless of your programming skill level, you'll go from basics to advanced concepts in a vast array of JavaScript subjects including Sammy.js, Agility.js, Ember.js, Node.js, jQuery, AJAX, Extjs, AngularJS, Knockout.js, and JSON.

    This is a guide to setting up a new WHM/cPanel Server to be used for web hosting accounts. It is intended for web hosting company administrators and dedicated server owners. For under $99 per month (considering normal rate of Big Data Cetnters like …
    One of the typical problems I have experienced is when you have to move a web server from one hosting site to another. You normally prepare all on the new host, transfer the site, change DNS and cross your fingers hoping all will be ok on new server…
    To add imagery to an HTML email signature, you have two options available to you. You can either add a logo/image by embedding it directly into the signature or hosting it externally and linking to it. The vast majority of email clients display l…
    Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

    875 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    14 Experts available now in Live!

    Get 1:1 Help Now