As mentioned already it's easy to implement this functionality with JLink.
But once you use Java's ZipOtputStream you will need to convert your data to list of bytes first. Borrowing java code from here.
<< JLink`
InstallJava[];
openStream[file_] := Module[{fos, bos, zos},
fos = JavaNew["java.io.FileOutputStream", file~StringJoin~".zip"];
bos = JavaNew["java.io.BufferedOutputStream", fos];
zos = JavaNew["java.util.zip.ZipOutputStream", bos];
zos@putNextEntry[JavaNew["java.util.zip.ZipEntry", file]];
zos];
closeStream[stream_] := Module[{},
stream@closeEntry[];
stream@close[];
];
stream = openStream["blah.dat"];
stream@write[{1, 2, 3}]
closeStream[stream];
As result you will get blah.dat.zip archive that will have blah.dat inside.
This is not very useful. We need some sort of serialization. Let's take your example and define
doStuff[x_] := x*x
We will store squares of 1-1000000 in a zip file:
convertToBytes[list_] :=
Flatten[ToCharacterCode /@ (ToString[#]~StringJoin~"\n" & /@ list)];
stream = openStream["blah.dat"];
stream@write[convertToBytes[doStuff /@ Range[1000000]]]
closeStream[stream];
Update @rcollyer proposed to hook into native streams with DefineOutputStreamMethod and it actually worked:
DefineOutputStreamMethod["Zipped", {
"ConstructorFunction" ->
Function[{name, isAppend, caller, opts}, {True, openStream[name]}],
"WriteFunction" ->
Function[{state, bytes}, state@write[bytes]; {Length[bytes], state}],
"CloseFunction" -> Function[{state}, closeStream[state]]
}];
Now we can work with zipped streams using native methods:
starWars = OpenWrite["star-wars.dat", Method -> "Zipped"];
Write[starWars, "yoda forever!"];
Write[starWars, {"Luke", "Leia"}];
Write[starWars, doStuff /@ Range[1000]];
Close[starWars];
$OutputStreamMethods. But I don't know how to get it to work. BTW you really should consider not usingForunless you can come up with a very good reason why it's appropriate. Just useDo. – Szabolcs Jan 02 '17 at 12:08Doinstead ofFor? – Stanislav Poslavsky Jan 02 '17 at 13:24,-;confusion), the iterator is not localized, it gets unnecessarily verbose (multiple iterators? list iterator?), it doesn't parallelize, etc. And it shows a bad example. A lot of beginner questions would just go away ifFordidn't exist in Mathematica. – Szabolcs Jan 02 '17 at 13:48StartProcessand an external compression program. – george2079 Jan 02 '17 at 14:15StartProcess:. 1) There is no evident way to direct the process standard out to a file. (this can be worked around) 2) I have been unable to figure out how to signal the end of the data. see http://mathematica.stackexchange.com/q/84430/2079 – george2079 Jan 03 '17 at 15:28