TextOutputStream
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... |
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.
Properties | ||
|
Methods | |||||
|
Shared Methods | ||
|
Constructors | |
|
Interfaces
The TextOutputStream class implements the Writeable class interface.
Notes
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.
If documents <> Nil Then
Var file As FolderItem = Documents.Child("Sample.txt")
If file <> Nil Then
Try
// 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
output.Write(TextField1.Text)
output.Close
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 output As TextOutputStream
file = FolderItem.ShowOpenFileDialog(FileTypes1.Text)
If file <> Nil then
output = TextOutputStream.Open(file)
output.Write(TextField1.Text)
output.Close
End If
This code writes to a new text file.
Var file As FolderItem = FolderItem.ShowSaveFileDialog("", "CreateExample.txt")
If file <> Nil Then
output = TextOutputStream.Create(file)
output.WriteLine(TextField1.Text)
output.Close
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.
If file <> Nil Then
Var fileStream As TextOutputStream
fileStream = TextOutputStream.Create(file)
fileStream.WriteLine(NameField.Text)
fileStream.WriteLine(AddressField.Text)
fileStream.WriteLine(PhoneField.Text)
fileStream.Close
End If
See Also
BinaryStream, FolderItem, IOException, TextInputStream, TextOutputStream classes; ConvertEncoding function; Encodings module; Writeable class interface.