Streams and compression
A stream is a flow of bytes that can come from memory, a file or the network. This lesson writes and reads a MemoryStream, compresses text with GZip, and shows why one pattern works for everything.
What you will learn#
- what a stream is and why .NET uses it everywhere,
MemoryStream,StreamWriterandStreamReader,Flush,PositionandDispose,- compressing and decompressing with
GZipStream, - the same code for memory and for files.
Streams in one minute#
A stream is like a pipe: bytes go in at one end and come out at the other. The same few classes work with every kind of pipe:
| Class | Source or target |
|---|---|
MemoryStream | memory |
FileStream | a file (File.Create, File.OpenRead) |
NetworkStream | a socket (the tutorial Sockets) |
GZipStream | wraps another stream and compresses or decompresses what passes |
StreamWriter / StreamReader | turn text into bytes and back |
Because they wrap each other you can stack them: text → StreamWriter → GZipStream → FileStream → disk.
The program#
# streams and compression - the same data in memory, in a file, and squeezed with GZip
load "dotnet.ring"
using {
"System"
"System.IO"
"System.IO.Compression"
"System.Text"
}
func main
oUtf8 = new Encoding().UTF8
# 1. A stream is a flow of bytes. A MemoryStream keeps them in memory: no file is needed to learn the pattern.
oMemory = new MemoryStream()
oWriter = new StreamWriter(oMemory)
oWriter.WriteLine("first line")
oWriter.WriteLine("second line")
oWriter.Flush() # the writer keeps a buffer: Flush sends it to the stream
? "1. bytes in the memory stream: " + oMemory.Length
# 2. Go back to the start and read what was written
oMemory.Position = 0
oReader = new StreamReader(oMemory)
? "2. read back: " + oReader.ReadLine() + " / " + oReader.ReadLine()
# 3. Compression: repeated text becomes much smaller. GZipStream wraps another stream: what you write is compressed on the way.
cText = ""
for nI = 1 to 200
cText += "The quick brown fox jumps over the lazy dog. "
next
aBytes = oUtf8.GetBytes(cText)
oPacked = new MemoryStream()
oGzipWriter = new StreamWriter((new GZipStream).@New([ :stream = oPacked, :mode = "Compress", :leaveOpen = True ]))
oGzipWriter.Write(cText)
oGzipWriter.Dispose() # Dispose finishes the compressed data: without it the result is incomplete
? nl + "3. " + len(aBytes) + " bytes became " + oPacked.Length + " bytes (" + floor(oPacked.Length * 100 / len(aBytes)) + " %)"
# 4. And back again: reading through a GZipStream decompresses
oPacked.Position = 0
oUnzip = new GZipStream(oPacked,"Decompress")
oBack = new StreamReader(oUnzip)
cBack = oBack.ReadToEnd()
? "4. the text is the same after the round trip: " + yesNo(cBack = cText)
# 5. Files are streams too: File.Create gives a FileStream, with the same Read/Write methods
cFile = new Path().Combine([new Path().GetTempPath(),"ringdotnet_streams.gz"])
oFileStream = new File().Create(cFile)
oFileGzip = new GZipStream(oFileStream,"Compress")
oFileWriter = new StreamWriter(oFileGzip)
oFileWriter.Write(cText)
oFileWriter.Dispose() # closes the writer, the GZipStream and the file
? nl + "5. the .gz file has " + new FileInfo(cFile).Length + " bytes"
new File().Delete(cFile)
func yesNo lValue
if lValue
return "yes"
ok
return "no"1. bytes in the memory stream: 25
2. read back: first line / second line
3. 9000 bytes became 120 bytes (1 %)
4. the text is the same after the round trip: yes
5. the .gz file has 120 bytesThis program uses a generic function (dnNew) where a class cannot be used. The lesson The generic functions explains them.
How it works#
Write, rewind, read#
Step 1 writes two lines into a MemoryStream. A StreamWriter keeps a buffer, so Flush() sends it to the stream before you look at Length. Step 2 sets Position = 0 to go back to the start (after writing, the position is at the end) and reads the lines with a StreamReader.
Compression#
The text of step 3 repeats the same sentence 200 times: 9,000 bytes become 120. Compression removes repetition, so text compresses very well and already compressed data (a zip, a JPEG) does not. A GZipStream created with "Compress" compresses what you write into it; with "Decompress" it decompresses what you read from it. Enum values are written as text ("Compress").
A compressing stream finishes its data only when it is disposed. Without Dispose() the end of the data is missing and the result cannot be read back. StreamWriter.Dispose() closes the stream under it too; the constructor option leaveOpen = True keeps the inner MemoryStream open so you can read it afterwards.
Files are streams too#
Step 5 stacks a StreamWriter on a GZipStream on a file created with File.Create. Disposing the writer closes everything below it. The pattern is the same as in memory.
What you learned#
- streams as pipes that can be stacked,
Flush,Position,Dispose,GZipStreamwith"Compress"and"Decompress",dnNew("GZipStream",[ :stream = ..., :mode = ..., :leaveOpen = True ])for a constructor with three values.
Exercises#
- Compress a text file to
.gzand decompress it to a new file, then compare the two with a hash (the tutorial Hashing and encryption). - Try
ZipArchiveto put several files in one zip. - Compress a text of 200 different lines and compare the size with the repeated text.