MATHEMATICA TUTORIAL

# Stream Methods

## Introduction

Input and output streams are opened using a stream method. A stream method abstracts the stream operations required for reading or writing bytes from the source of those bytes. This makes it possible to read or write from data sources and storage mechanisms such as files, child processes, web servers, and in-memory lists of bytes. A stream method can also perform translations such as compression or encryption. For example, a stream method could allow a user to open a compressed file and read the uncompressed contents. Operating on streams allows operations to be performed on very large files that could otherwise not fit into physical memory.

Mathematica supplies stream methods for the most common needs, such as reading and writing from files, web servers, strings, and external commands. New stream methods can also be added to Mathematica.

## Using Stream Methods

When you open a stream for reading or writing, you can specify the stream method with the Method option, or Mathematica can choose the stream method automatically from the stream name.

This opens a stream from a web server, selecting the stream method from the stream name.
 Out[6]=
 Out[7]=
 Out[9]=
This opens a stream from a web server, selecting the stream method with the Method option.
 Out[52]=
 Out[53]=
 Out[54]=
This loads a Mathematica package directly from a web server, selecting the stream method from the stream name:
 Out[11]=
This loads a Mathematica package directly from a web server, using an explicitly opened input stream:
 Out[27]=
 Out[30]=
 Out[31]=

## Input Stream Methods

You can add new input stream methods to Mathematica. This would be useful if you wanted to read from a new storage medium, or you wanted to transform the data as it is read, such as uncompressing a file.

Define a stream method that takes its input not from a file but from a list of bytes, passed as a method option :
 Out[27]=
This tests the new method.
 Out[34]//InputForm=
This defines a stream method that performs a rotation cipher on the stream as it reads. A cryptographically strong decryption could be performed in the same fashion.
Test the method by first writing an enciphered test file, and then reading it using the new method.
 Out[58]=
 Out[60]=
The file content differs from what Read returns, because the stream method translates it.
 Out[61]=
 Out[62]=

## Output Stream Methods

You can add new output stream methods to Mathematica. This would be useful if you wanted to write to a new storage medium, or you wanted to transform the data as it is written, such as compressing a file.

This defines a minimal stream method that prints the number of bytes written.
 Out[20]=
This tests the new method.
 Out[21]=
 Out[22]=
 Out[23]=
 Out[24]=
 Out[25]=
New to Mathematica? Find your learning path »
Have a question? Ask support »