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 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.


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.

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.Write(ConvertEncoding(TextField1.Value, Encodings.UTF8))
Catch e As IOException
// handle
End Try
End If
End If

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.