Question

How do you compress a directory in Squeak Smalltalk? I found the compressFile method in StandardFileStream but I can't figure out how to compress multiple files or a directory. I experimented with the System-Compression classes but haven't had much luck. Thanks in advance!

This is what I have now. I'm adding time stamps at the end of file names, so here I want to put all files that begin with the given file name into a zip or gzip file.

compressFile: aFileName in: aDirectory

| zipped buffer unzipped zipFileName |
zipFileName _ aFileName copyUpTo: $. .
zipped _ aDirectory newFileNamed: (zipFileName, FileDirectory dot, 'zip').
zipped binary; setFileTypeToObject.
zipped _ ZipWriteStream on: zipped.
buffer _ ByteArray new: 50000.  
aDirectory fileNames do: [:f |
    (f beginsWith: zipFileName) ifTrue: [
        unzipped _ aDirectory readOnlyFileNamed: (aDirectory fullNameFor: f).
        unzipped binary.
        [unzipped atEnd] whileFalse:[
            zipped nextPutAll: (unzipped nextInto: buffer)].
        unzipped close]].
zipped close.
Was it helpful?

Solution

ZipWriteStream is only a helper class used for compressing, it does not know how a proper ZIP file is layed out, with all the header and directory information etc. You want to use the ZipArchive class.

"first, construct archive layout in memory"
zip := ZipArchive new.
zip addFile: 'foo.txt'.
zip addFile: 'bar.txt' as: 'xyz.txt'.
zip addTree: dir match: [:entry | entry name beginswith: 'baz'].
"then, write archive to disk, compressing each member"
file := dest newFileNamed: 'test.zip'.
zip writeTo: file.
file close.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top