Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating zip files in Pharo

How can one create zip files in Pharo and write them to disk?

I thought I could create the structure in a MemoryStore and then zip it as following

root := FileSystem memory root ensureCreateDirectory.

root / 'sample.txt' writeStreamDo: [ :stream | stream << String loremIpsum ].

archive := ZipArchive new.
root allChildren select: #isFile thenDo: [ :each |
    each readStreamDo: [ :readStream |
        archive addString: readStream contents as: each fullName
    ]
].
archive writeTo: someFinalWriteStream.

archive close.

But apparently data added via addString:as: is not compressed at all.

Likewise addFile:/addFile:as: is not usable, because the implementation works only with real disk, not memory one.

So is there some other approach (or external library) with which I can zip my data without without having to dump all files to disk, zipping it there and reading the final file back?

like image 480
Peter Uhnak Avatar asked Nov 23 '25 18:11

Peter Uhnak


1 Answers

Try something on the lines of:

string := String new: 14 withAll: $1.
archive := ZipArchive new.
member := zip addDeflateString: string as: 'filename.ext'.
member instVarNamed: 'compressionMethod' put: 8.
member rewindData.
zip := ByteArray streamContents: [:strm | member compressDataTo: strm].

Note that I've forced the setting of compressionMethod, there must be a better way to do this, and I'm sure you will find it ;)

like image 70
Leandro Caniglia Avatar answered Nov 26 '25 10:11

Leandro Caniglia