Month: February 2013

PeopleCode: Unzipping

I come upon a requirement to unzip a file in a platform independent way.  Jim Marion got me most of the way, but his code didn’t write it to file.  Here’s my adjustment to make a function that wrote it to file:

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
Function unzip(&inputZipFile, &targetDir)
  Local JavaObject &zipFileInputStream = CreateJavaObject("java.io.FileInputStream", &inputZipFile);
  Local JavaObject &zipInputStream = CreateJavaObject("java.util.zip.ZipInputStream", &zipFileInputStream);
  Local JavaObject &zipEntry = &zipInputStream.getNextEntry();
  Local JavaObject &buf = CreateJavaArray("byte[]", 1024);
  Local number &byteCount;
 
  While &zipEntry <> Null
 
    If (&zipEntry.isDirectory()) Then
      REM ** do nothing;
    Else
      Local JavaObject &outFile = CreateJavaObject("java.io.File", &targetDir | &zipEntry.getName());
      &outFile.getParentFile().mkdirs();
      Local JavaObject &out = CreateJavaObject("java.io.FileOutputStream", &outFile);
      &byteCount = &zipInputStream.read(&buf);
 
      While &byteCount > 0
        &out.write(&buf, 0, &byteCount);
        &byteCount = &zipInputStream.read(&buf);
      End-While;
 
      &zipInputStream.closeEntry();
    End-If;
 
    &zipEntry = &zipInputStream.getNextEntry();
  End-While;
 
  &zipInputStream.close();
  &zipFileInputStream.close();
End-Function;
 
unzip("/tmp/myzipfile.zip", "/tmp/out");

Resources