Wiki

root/cobra/trunk/HowTo/275-ReadAndWriteFiles.cobra

Revision 2460, 1.0 KB (checked in by Chuck.Esterbrook, 18 months ago)

Code cleanup.

  • Property svn:eol-style set to native
Line 
1"""
2Reading files in Cobra relies on the libraries and therefore is pretty the much
3the same as C# or VB.
4
5See the BCL (Base Class Library) docs for File, StreamReader, StreamWriter,
6TextReader and TextWriter for more.
7"""
8
9
10class Test
11
12    def main
13        nl = CobraCore.newLine
14        fileName = 'test-file.text'
15
16        # write a whole file
17        File.writeAllText(fileName, 'This is a test file.[nl]To make sure there is a file to work with.[nl]')
18
19        # read a whole file
20        contents = File.readAllText(fileName)
21        assert 'test' in contents   # The `in` operator works for strings: <substring> in <string> ==> bool
22
23        # read line by line
24        num = 1
25        using sr = File.openText(fileName)
26            while true
27                line = sr.readLine
28                if line is nil, break
29                print '[num]. len=[line.length] "[line.trim]"'
30                num += 1
31
32        # be nice about IO errors
33        fileName = 'bad-file-name.text'
34        try
35            contents = File.readAllText(fileName)
36        catch ioe as IOException
37            print 'I/O Error: [ioe.message]'
38        success
39            assert 'test' in contents
Note: See TracBrowser for help on using the browser.