Zip files are a common file format for sharing collections of files or for compressing large files. I’m going to take a look at how JSL can be used to handle these files without first manually unzipping the file.
The Zip Archive Object
Version 12 of JMP introduced the Zip Archive object for manipulating zip files. A zip archive object is created using the Open function with the zip keyword:
1 |
za = open("Data.zip", zip); |
Interrogating the Zip File
The first thing that we might want to do is to determine the contents of the zip file. The dir message can be sent to a zip archive object to product a directory list of the contents:
Opening the First JMP Table
To read the contents of the first JMP table within the zip file I can send the read message to the zip archive object:
1 |
blobdata = za << read( lst[1], format(blob) ) |
The JMP file is in a binary format, not straight text. I deal with that by adding ‘format(blob)’ to the message. The data that describes the contents of this file is contained in a variable that I have named blobdata.
To create the physical file I need to save this data:
1 2 |
path = “c:\documents\” || lst[1]; savetextfile(path,blobdata) ; |
Now I can access the JMP data in the usual way:
1 |
dt = open(path); |
Processing the Entire Zip File
Now that I have established the code framework for handling the contents of the zip file, I can iterative over all of the contained files:
1 2 3 4 5 6 7 |
za = open("Data.zip", zip); lst = za << dir; for (i=1,i<=nitems(lst),i++, blobdata = za << read(lst[i],format(blob)); path = “c:\documents\” || lst[i]; savetextfile(path,blobdata); ); |
An Extended Example
Let’s say that I want to perform the following tasks:
- Allow the user to select the zip file
- Present the user a list of files contained within the zip file
- Allow the user to select a file
- Open the selected file
Here is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
namesdefaulttohere(1); // let the user pick the zip file zipPath = pickfile("Select File:",,{"Zip Files|zip"}); if (ismissing(zipPath),throw()); // list contents of zip file za = open(zipPath,zip); lst = za << dir; // let the user select a file from the list nw = NewWindow("Selection",<<modal, <<onClose( sel = lb << getSelected ), BorderBox(top(10),bottom(20),left(20),right(20), VListBox( TextBox("Select a file:"), SpacerBox(size(0,6)), lb = ListBox(lst,maxselected(1)), ) ) ); if (nw["Button"]==-1,throw()); // grab the name of the file from the list selection if (nitems(sel)>0, file = sel[1] , throw() ); // unzip the file blob = za << read(file,format(blob)); // open the table filePath = convertfilepath(file,base("$TEMP")); show(filePath); savetextfile(filePath,blob); dt = open(filePath); |