TextInputStream
From Xojo Documentation
Supported Platforms Project Types: Desktop Platforms: macOS, Windows, Linux |
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. If you are working with a file with an encoding that is not UTF-8, you should set the value of the Encoding property.
Properties | ||
|
Methods | ||||||
|
Shared Methods | |
|
Constructors | |
|
Notes
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:
If f <> Nil Then
If f.Exists Then
// Be aware that TextInputStream.Open could raise an exception
Var t As TextInputStream
Try
t = TextInputStream.Open(f)
t.Encoding = Encodings.UTF8
TextArea1.Value = t.ReadAll
Catch e As IOException
MessageBox("Error accessing file.")
End Try
t.Close
End If
End If
To specify the encoding, you could instead use optional parameter of the ReadAll method:
instead of
Sample Code
This example reads the rows and columns of data from a tab-delimited text file into a ListBox:
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)
textInput.Encoding = Encodings.MacRoman // strings are MacRoman
While Not textInput.EndOfFile
rowFromFile = textInput.ReadLine
// Set
If ListBox1.ColumnCount < rowFromFile.CountFields(tab) Then
ListBox1.ColumnCount = rowFromFile.CountFields(tab)
End If
ListBox1.AddRow("")
For i = 1 To rowFromFile.CountFields(tab)
oneCell = rowFromFile.NthField(tab, i)
ListBox1.CellValueAt(ListBox1.LastAddedRowIndex, i - 1) = oneCell
Next
Wend
textInput.Close
End If
See Also
ConvertEncoding, DefineEncoding, Encoding functions; BinaryStream, IOException, TextEncoding, TextOutputStream classes; Encodings module; Readable class interface.