From Xojo Documentation

Class (inherits from Object)

In order to write text to a file, you need to create a TextOutputStream object. TextOutputStreams have methods that allow to write to a file and close the file when you are done writing to it. They are created by calling the Create and Append shared methods. If you need to specify the encoding of the text, call ConvertEncoding prior to writing the file.

Delimiter Handle fa-lock-32.png LastErrorCode fa-lock-32.png
Close Write WriteLine
Flush WriteError
Shared Methods
Append Create

TextOutputStream.Constructor(handle as Integer, type as Integer)

Class Constants

The following class constants can be used to specify the optional type parameter in the constructor and the Handle property.

Class Constant Description
HandleTypeWin32Handle A Windows 32 OS handle
HandleTypeFilePointer A file pointer.
HandleTypeFileNumber A file descriptor.
HandleTypeMacFileRefNum A file reference number
HandleTypeMacFileSpecPointer An FSSpec.


The TextOutputStream class implements the Writeable class interface.


If you need to write the file using a particular encoding, use the ConvertEncoding function to first convert the encoding of the text to the desired encoding before passing the text to the Write or WriteLine methods.

Dim Documents As FolderItem = SpecialFolder.Documents
If Documents <> Nil Then
Dim f As FolderItem = Documents.Child("Sample.txt")
If f <> Nil Then
// TextOutputStream.Create raises an IOException if it can't open the file for some reason.
Dim t As TextOutputStream = TextOutputStream.Create(f)
t.Write(ConvertEncoding(TextField1.Text, Encodings.UTF8))
Catch e As IOException
// handle
End Try
End If
End If

Creating and Appending to a Text File

Use Append when you want to open an existing text file and append text data to it. Use Create to write to a new text file. The following two examples illustrate the difference. Each example writes the text in TextField1 to the text file.

This code appends the text in TextField1 to the text file that was opened by GetOpenFolderItem:

Dim f As FolderItem
Dim t As TextOutputStream
f = GetOpenFolderItem(FileTypes1.Text)
If f <> Nil then
t = TextOutputStream.Append(f)
End If

This code writes to a new text file.

Dim t As TextOutputStream
Dim f As FolderItem
f = GetSaveFolderItem("", "CreateExample.txt")
If f <> Nil Then
t = TextOutputStream.Create(f)
End If

Sample Code

This code displays the Save As dialog box. A text file is then created and the text properties of three TextFields are written to the new file. Finally the file is closed.

Dim file As FolderItem
Dim fileStream As TextOutputStream
file = GetSaveFolderItem("", "MyInfo.txt")
If file <> Nil Then
fileStream = TextOutputStream.Create(file)
End If

See Also

BinaryStream, FolderItem, IOException, TextInputStream, TextOutputStream classes; ConvertEncoding function; Encodings module; Writeable class interface.