From Xojo Documentation

Class (inherits from Object)

In order to read text from a file, you need to create a TextInputStream object. TextInputStreams have methods that allow to read from a file, check to see if you are at the end of the file, and close the file when you are done reading from it. They are created by calling the Open shared method.

BytePosition Encoding
Close Handle ReadAll
EndOfFile Read ReadLine
Shared Methods

Constructor(handle as Ptr, type as IOStreamHandleTypes)


When reading a file, the default encoding is UTF8.

When you read a text file that is from another operating system or in another language (or a mixture of languages) you may need to specify the text encoding that was used when the file was written. If you know the encoding, use the Encodings module to get the encoding and use it to set the value of the Encoding property of the TextInputStream object. Here is an example that reads a text file that uses the MacRoman encoding:

Var f As FolderItem = FolderItem.ShowOpenFileDialog("text") // as defined in File Type Sets Editor
If f <> Nil Then
If f.Exists Then
// Be aware that TextInputStream.Open could raise an exception
Var t As TextInputStream
t = TextInputStream.Open(f)
t.Encoding = Encodings.MacRoman
TextArea1.Value = t.ReadAll
Catch e As IOException
MessageBox("Error accessing file.")
End Try
End If
End If

To specify the encoding, you could instead use optional parameter of the ReadAll method:

TextArea1.Value = t.ReadAll(Encodings.MacRoman)

instead of

t.Encoding = Encodings.MacRoman

Sample Code

This example reads the rows and columns of data from a tab-delimited text file into a ListBox:

Var f As FolderItem
Var textInput As TextInputStream
Var rowFromFile, oneCell As String
Var i As Integer
f = FolderItem.ShowOpenFileDialog("text/plain") // defined as a FileType
If f <> Nil And f.Exists Then
Var tab As String = ChrB(9)
textInput = TextInputStream.Open(f)
While Not textInput.EndOfFile
rowFromFile = textInput.ReadLine

// Set
If ListBox1.ColumnCount < rowFromFile.CountFields(tab) Then
ListBox1.ColumnCount = rowFromFile.CountFields(tab)
End If

For i = 1 To rowFromFile.CountFields(tab)
oneCell = rowFromFile.NthField(tab, i)
ListBox1.CellValueAt(ListBox1.LastAddedRowIndex, i - 1) = oneCell
End If

See Also

ConvertEncoding, DefineEncoding, Encoding functions; BinaryStream, IOException, TextEncoding, TextOutputStream classes; Encodings module; Readable class interface.