TextOutputStream
From Xojo Documentation
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.
Properties | |
|
Methods | |||||
|
Shared Methods | ||
|
Constructors | |
|
Interfaces
The TextOutputStream class implements the Writeable class interface.
Notes
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.
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.Write(ConvertEncoding(TextField1.Value, Encodings.UTF8))
output.Close
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 output As TextOutputStream
file = FolderItem.ShowOpenFileDialog(FileTypes1.Text)
If file <> Nil then
output = TextOutputStream.Open(file)
output.Write(TextField1.Value)
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.Value)
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.Value)
fileStream.WriteLine(AddressField.Value)
fileStream.WriteLine(PhoneField.Value)
fileStream.Close
End If
See Also
BinaryStream, FolderItem, IOException, TextInputStream, TextOutputStream classes; ConvertEncoding function; Encodings module; Writeable class interface.