Class

TextInputStream


Description

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.

Properties

Name

Type

Read-Only

Shared

BytePosition

UInt64

Encoding

TextEncoding

Methods

Name

Parameters

Returns

Shared

Close

Constructor

handle As Ptr, type As IOStreamHandleTypes

EndOfFile

Boolean

Handle

type As IOStreamHandleTypes

Ptr

Open

file As FolderItem

TextInputStream

Read

Count As Integer, encoding As TextEncoding = Nil

String

ReadAll

encoding As TextEncoding = Nil

String

ReadError

Boolean

ReadLine

encoding As TextEncoding = Nil

String

Property descriptions


TextInputStream.BytePosition

BytePosition As UInt64

Indicates the byte position of the file pointer, not the character position.


TextInputStream.Encoding

Encoding As TextEncoding

Specifies the encoding to be defined for a string returned by ReadLine or ReadAll.

It does not actually convert the bytes, but only assigns them an encoding, as if you had called DefineEncoding. Use the Encoding object to specify the TextEncoding. It defaults to UTF-8, but you can assign it a different encoding to match your file, or even assign Nil if you want the string to have an undefined encoding.

This example sets the encoding for a file:

Var f As FolderItem = SpecialFolder.Documents.Child("test.txt")
Var t As TextInputStream = TextInputStream.Open(f)
t.Encoding = Encodings.UTF8

Method descriptions


TextInputStream.Close

Close

Closes the file.


TextInputStream.Constructor

Constructor(handle As Ptr, type As IOStreamHandleTypes)

Note

Constructors are special methods called when you create an object with the New keyword and pass in the parameters above.

Creates a TextInputStream instance.

Important

This method is not supported for Android.

Type is one of the IOStreamHandleTypes and Handle is the appropriate handle type specified by the Type parameter.

For instance, you can use a Declare to open a file with whatever permissions that you wish, and then pass the Handle to a stream object's constructor.


TextInputStream.EndOfFile

EndOfFile As Boolean

Returns True when there's no more data left to read.

This code 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 As String

f = FolderItem.ShowOpenFileDialog("text/plain") ' defined as a FileType
If f <> Nil Then
  textInput = TextInputStream.Open(f)
  textInput.Encoding = Encodings.UTF8

  Do
    rowFromFile = textInput.ReadLine
    Var values() As String = rowFromFile.ToArray(String.Chr(9))
    ListBox1.ColumnCount = values.Count
    ListBox1.AddRow("")
    Var col As Integer
    For Each value As String In values
      ListBox1.CellTextAt(ListBox1.LastAddedRowIndex, col) = value
      col = col + 1
    Next
  Loop Until textInput.EndOfFile

  textInput.Close
End If

This example reads each pair of bytes from a file and writes them in reverse order to a new file. The user chooses the source file using the Open-file dialog box and saves the new file using the Save as dialog box. The EOF property is used to terminate the Do...Loop.

Var readFile As FolderItem = FolderItem.ShowOpenFileDialog("text")
If readFile <> Nil Then
  Var ReadStream As BinaryStream = BinaryStream.Open(readFile, False)
  ReadStream.LittleEndian = True
  Var writeFile As FolderItem = FolderItem.ShowSaveFileDialog("", "")
  If writeFile <> Nil Then
    Var writeStream As BinaryStream = BinaryStream.Create(writeFile, True)
    writeStream.LittleEndian = True
    Do Until ReadStream.EndOfFile
      writeStream.WriteInt8(ReadStream.ReadInt8)
    Loop
    writeStream = Nil
  End If
  readStream = Nil
End If

TextInputStream.Handle

Handle(type As IOStreamHandleTypes) As Ptr

Handle returns a handle of the Type passed or -1 if the requested Type cannot be retrieved.

Important

This method is not supported for Android.

See IOStreamHandleTypes for a list of valid types.


TextInputStream.Open

Open(file As FolderItem) As TextInputStream

Opens the passed FolderItem to be read as a text file. Returns a TextInputStream. An IO error will trigger an IOException.

This method is shared.

Reading from the file will begin at the start of the file. If you wish to read from any other point in the file, use the BytePosition property to move the read position.

This shared method replaces the deprecated FolderItem.OpenAsTextFile.

Var f As FolderItem
Var t As TextInputStream
f = FolderItem.ShowOpenFileDialog("text") ' file type defined in File Type Sets Editor
If f <> Nil Then
  t = TextInputStream.Open(f)
  t.Encoding = Encodings.UTF8 //specify encoding of input stream
  TextArea1.Text = t.ReadAll
  t.Close
End if

TextInputStream.Read

Read(Count As Integer, encoding As TextEncoding = Nil) As String

Reads Count bytes from the input stream and returns a String.

If provided, the optional parameter Enc specifies the text encoding to be defined for the String to be read.

If Count is higher than the amount of bytes currently available in the stream, all available bytes will be returned. Therefore, make sure to always consider the case that you get less than you requested. To see if you received all requested bytes, check the returned string's String property (avoid using Length as it may give a different number if the encoding is not nil).

If not enough memory is available, you get back an empty string.

This example reads the first 1000 bytes from a BinaryStream.

Var readFile As FolderItem = FolderItem.ShowOpenFileDialog("text/plain")
If readFile <> Nil Then
  Var ReadStream As BinaryStream = BinaryStream.Open(readFile, False)
  ReadStream.LittleEndian = True
  TextArea1.Text = ReadStream.Read(1000, Encodings.UTF8)
End If

TextInputStream.ReadAll

ReadAll(encoding As TextEncoding = Nil) As String

Returns all of the text from the current position to the end of the file as a String.

The optional Encoding parameter enables you to specify the encoding of the text. If you pass Nil, the default encoding is used. This is usually UTF-8, unless it was set to another encoding via an assignment statement. If you want to set the encoding to Nil, use the Encoding property instead.

This example is opens a text file that the user selects into a TextInputStream and then displays it in a TextArea.

Var f As FolderItem
Var dlg As OpenDialog
Var t As TextInputStream

' create a new openDialog
dlg = New OpenDialog
' set what type of file it looks for
dlg.Filter = "text/plain"

' display the dialog
f = dlg.ShowModal

' check to make sure the user didn't click cancel
If f <> Nil Then
  t = TextInputStream.Open(f)
  ' make sure we could open it
  If t <> Nil Then
    ' Read all of t into myTextArea.text
    MyTextArea.Text = t.ReadAll
    ' close the file so that other applications can use it
    t.Close
  Else
    ' the file could not be a read as a text file
    MessageBox("The selected file is not a text file.")
  End If
Else
  ' the user clicked cancel... just ignore it
End If

TextInputStream.ReadError

ReadError As Boolean

If True then an error occurred during reading.


TextInputStream.ReadLine

ReadLine(encoding As TextEncoding = Nil) As String

Returns the next line of text (as a string) from the TextInputStream. Any valid end-of-line indicator is used to identify a line.

The optional Encoding parameter enables you to specify the encoding of the text. If you pass Nil, the default encoding is used. This is usually UTF-8, unless it was set to another encoding via an assignment statement. If you want to set the encoding to Nil, use the Encoding property instead.

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

Const kTab As String = &u9

Var f As FolderItem
Var textInput As TextInputStream
Var rowFromFile, oneCell As String

f = FolderItem.ShowOpenFileDialog("text/plain") ' defined as a FileType
If f <> Nil Then
  textInput = TextInputStream.Open(f)
  textInput.Encoding = Encodings.UTF8
  Do
    rowFromFile = textInput.ReadLine
    If ListBox1.ColumnCount < rowFromFile.CountFields(kTab) Then
      ListBox1.ColumnCount = rowFromFile.CountFields(kTab)
    End If

    ListBox1.AddRow(rowFromFile.NthField(kTab, 1))
    For i As Integer =1 To rowFromFile.CountFields(kTab)
      oneCell = rowFromFile.NthField(kTab, i)
      ListBox1.CellTextAt(ListBox1.SelectedRowIndex - 1, i - 1) = oneCell
    Next
  Loop Until textInput.EndOfFile
  textInput.Close
End If

Interfaces

The TextInputStream class implements the Readable class interface.

Notes

When reading a file, the default encoding is UTF8. If the file has no encoding, read it instead with a BinaryStream.

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
    Try
      t = TextInputStream.Open(f)
      t.Encoding = Encodings.MacRoman
      TextArea1.Text = 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:

TextArea1.Text = 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 DesktopListBox:

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 = String.ChrByte(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

    ListBox1.AddRow("")
    For i = 1 To rowFromFile.CountFields(tab)
      oneCell = rowFromFile.NthField(tab, i)
      ListBox1.CellTextAt(ListBox1.LastAddedRowIndex, i - 1) = oneCell
    Next
  Wend
  textInput.Close
End If

Compatibility

All project types on all supported operating systems.

See also

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