Extend TextInputStream With a ReadLines Method
· Nov 6, 10:19 AMOften you want to read in the entire contents of a text file split into lines. The TextInputStream class has methods to read a single line, or to read all of the text into a single String. You could call ReadAll, followed by Split, but that requires you to handle the choice of line endings yourself instead of letting TextInputStream handle it. And it is code that you would need to write more than once. A better approach is to add a ReadLines method to TextInputStream using extends.
I use the extends mechanism to add lots of methods to existing classes and datatypes. For purposes of organization, I create a module for each class or datatype with a name like TextInputStreamExtension, and use it solely for storage of extension methods.
Here is the function.
Function ReadLines(extends t as TextInputStream, encoding as TextEncoding = nil) As String()
dim textLines() as String
do until t.EOF
textLines.Append t.ReadLine(encoding)
loop
return textLines
End Function
Now you can write code like
dim logFile as FolderItem = GetFolderItem('/var/log/foo.log', FolderItem.PathTypeShell)
if logFile is nil then
//handle
end if
dim t as TextInputStream = logFile.OpenAsTextFile
if t is nil then
//check logFile.LastErrorCode
end if
dim logEntries() as String = t.ReadLines
t = nil
//process log entries
Commenting is closed for this article.
A REALSQLDatabase.LastRowID Workaround Extend TextInputStream With a ReadParagraph Method