From Xojo Documentation

You are currently browsing the old Xojo documentation site. It will go offline as of October 2, 2023. Please visit the new Xojo documentation site! - you will be redirected shortly...

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.

Delimiter Encoding
Close Handle WriteLine
Flush Write
Shared Methods
Create Open

Constructor(handle as Ptr, type as IOStreamHandleTypes)


The TextOutputStream class implements the Writeable class interface.


Setting the Text Encoding

The default encoding is UTF8. If you want no encoding, use a BinaryStream. If you need to write a file using a different encoding, use the Encoding property before passing the text to the Write or WriteLine methods.

Var documents As FolderItem = SpecialFolder.Documents
If documents <> Nil Then
Var file As FolderItem = Documents.Child("Sample.txt")
If file <> Nil Then
// TextOutputStream.Create raises an IOException if it can't open the file for some reason.
Var output As TextOutputStream = TextOutputStream.Create(file)
output.Encoding = Encodings.WindowsANSI
Catch e As IOException
// handle
End Try
End If
End If

All available encodings are in the Encodings module.

Creating and Appending to a Text File

Use Open when you want to open an existing text file and add 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 FolderItem.ShowOpenFileDialog:

Var file As FolderItem
Var output As TextOutputStream
file = FolderItem.ShowOpenFileDialog(FileTypes1.Text)
If file <> Nil then
output = TextOutputStream.Open(file)
End If

This code writes to a new text file.

Var output As TextOutputStream
Var file As FolderItem = FolderItem.ShowSaveFileDialog("", "CreateExample.txt")
If file <> Nil Then
output = TextOutputStream.Create(file)
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.

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

See Also

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