Text readers and writers
StringWriter and StringReader are text streams that live in memory. This lesson uses them to write code that works with any writer (a string, a file, the console), to read text line by line, to capture the output of code that prints, and to format text with String.Format.
What you will learn#
StringWriterandStringReader,- the base classes
TextWriterandTextReader, and why a function should take one, - reading line by line with
ReadLineandPeek, Console.SetOutto capture output,- composite formatting with
String.Format({0}, alignment, formats).
The tutorial Files and folders wrote and read files and the tutorial Streams and compression explained streams. A string can be a stream too, and that is very useful.
The program#
# text readers and writers - StringWriter and StringReader, TextWriter in functions, and capturing Console output
load "dotnet.ring"
using {
"System"
"System.IO"
"System.Text"
}
func main
# 1. A StringWriter is a TextWriter that writes into a string in memory. Code that writes to "a TextWriter" does not care whether it
# is a file, the console or a string: that makes it easy to test and to reuse.
oWriter = new StringWriter
oWriter.WriteLine("first line")
oWriter.Write("second ")
oWriter.Write("line")
oWriter.WriteLine(NULL)
oWriter.WriteLine("third line")
cText = substr(oWriter.ToString(),char(13),"") # (Windows ends a line with two characters, Linux with one: the same text is shown)
aLines = str2list(cText)
? "1. the writer collected three lines of text:"
for cLine in aLines
if cLine != ""
? " " + cLine
ok
next
# 2. StringReader reads a string line by line or all at once, like a file. Peek looks at the next character without taking it:
# -1 means that nothing is left
oReader = new StringReader("alpha" + nl + "beta" + nl + "gamma")
? nl + "2. reading line by line:"
nNumber = 0
while oReader.Peek() != -1
nNumber++
? " " + nNumber + ": " + oReader.ReadLine()
end
oReader.Dispose()
oRest = new StringReader("12 apples")
? " ReadToEnd gives the whole text: " + oRest.ReadToEnd()
# 3. A function that writes its report to ANY writer. The same function is used for a string and for a file.
? nl + "3. the same report function with two kinds of writer:"
oToString = new StringWriter
writeReport(oToString,"Ann",31)
? " to a string: " + substr(substr(oToString.ToString(),char(13),""),nl," | ")
cFile = new Path().Combine([new Path().GetTempPath(),"ringdotnet_readers.txt"])
oFileWriter = new StreamWriter(cFile)
writeReport(oFileWriter,"Bob",28)
oFileWriter.Dispose()
? " to a file: " + substr(substr(new File().ReadAllText(cFile),char(13),""),nl," | ")
new File().Delete(cFile)
# 4. Console.SetOut sends what a program writes with Console.WriteLine into a writer instead of the screen: that is how a test can
# check the output of code that prints. (Ring's own ? statement writes through the C library, not through Console.)
oCapture = new StringWriter
oConsole = new Console()
oOld = oConsole.Out # the real console writer: it must be put back
oConsole.SetOut(oCapture)
oConsole.WriteLine("hidden message 1")
oConsole.WriteLine("hidden message 2")
oConsole.SetOut(oOld)
? nl + "4. captured, not shown on the screen: " + substr(substr(oCapture.ToString(),char(13),""),nl," | ")
# 5. Composite formatting: String.Format puts values into {0}, {1} places, with formats after a colon
oString = new String()
? nl + "5. " + oString.Format([ :format = "{0} bought {1} items for {2:0.00}", :args = ["Ann",3,12.5] ])
? " alignment: [" + oString.Format([ :format = "{0,-8}|{1,8}", :args = ["left","right"] ]) + "]"
? " padded numbers: " + oString.Format([ :format = "{0:00000} {1:0.0} {2:0.##} {3:D5} {4:X4}", :args = [42,255,0.25,42,255] ])
func writeReport oWriter,cName,nAge
oWriter.WriteLine("name: " + cName)
oWriter.WriteLine("age: " + nAge)1. the writer collected three lines of text:
first line
second line
third line
2. reading line by line:
1: alpha
2: beta
3: gamma
ReadToEnd gives the whole text: 12 apples
3. the same report function with two kinds of writer:
to a string: name: Ann | age: 31 |
to a file: name: Bob | age: 28 |
4. captured, not shown on the screen: hidden message 1 | hidden message 2 |
5. Ann bought 3 items for 12.50
alignment: [left | right]
padded numbers: 00042 255.0 0.25 00042 00FFHow it works#
StringWriter#
A StringWriter has the same methods as a StreamWriter (Write, WriteLine), but it collects the text in memory; ToString() gives it back. Use it to build a longer text piece by piece, and above all as a test double for a file or the console. WriteLine(NULL) ends the current line without adding text. (Windows ends a line with two characters, CR LF, and Linux with one, LF; the program removes char(13) so the output is the same everywhere.)
StringReader#
StringReader reads a text like a file: ReadLine gives one line, ReadToEnd the rest. It has no EndOfStream; Peek() answers the next character without taking it, and -1 means that nothing is left, so while oReader.Peek() != -1 reads all the lines.
One function, many writers#
StringWriter and StreamWriter both derive from TextWriter. The function writeReport(oWriter, ...) only calls WriteLine, so it does not know where the text goes: step 3 calls it with a string and with a file and gets the same report. This is a good habit for your own functions: take a writer as a parameter instead of writing to a fixed place. The function is then easy to test (give it a StringWriter and look at the result) and easy to reuse (give it a network stream). The same is true for readers and TextReader.
Capturing the console#
Console.SetOut(writer) redirects everything that .NET code writes with Console.WriteLine into a writer; the program saves the old writer (Console.Out) first and puts it back, because forgetting that hides every later message. It is the way to check the output of a .NET method that prints. Ring's own ? and see do not go through Console, so they are not captured.
Composite formatting#
String.Format("{0} bought {1} items for {2:0.00}", args) puts the values into numbered places. After a colon comes a format: 0.00 is two decimals (12.50), 00000 pads with zeros (00042), 0.## shows up to two decimals and no more (0.25). The format P0 writes a percentage, but where the % goes depends on the culture of the computer (25% or 25 %), so a test must not compare it as text. A comma sets the width: {0,-8} is left-aligned in 8 characters and {1,8} right-aligned. The method has several forms, so it takes names (:format and :args). A whole number from Ring is an Int32 in the array, so D5 (zeros in front) and X4 (hexadecimal) work for it; a number with a fraction is a Double, and those two formats raise Format specifier was invalid for it.
What you learned#
StringWriterandStringReaderfor text in memory,PeekandReadLineto read all lines,- functions that take a
TextWritercan write anywhere, Console.SetOutcaptures output (and must be undone),String.Formatwith places, alignment and formats.
Exercises#
- Write
numberedLines(oReader, oWriter)that copies a text and puts a line number before each line. - Write a test that captures the output of
Console.WriteLineand checks it. - Make a table with
String.Formatand aligned columns for a list of products and prices. - Read a CSV text with
StringReaderand cut each line into fields with Ring (str2list(substr(cLine,",",nl)), see the tutorial Working with text).