I am trying to have a textarea display the contents of a .txt file that has been created in the project folder called “List.txt” (Without an OpenDialog).
In a buttons “Action” event I have the following code.
Var f As FolderItem
f = New FolderItem("List.txt")
if f.Exists then
TextArea1.text = f
end if
I know this code is probably very wrong (as it doesn’t work). I am still trying to grasp folderitems and the such.
Var f As FolderItem = FolderItem.ShowOpenFileDialog("text") // as defined in File Type Sets Editor
If f <> Nil Then
If f.Exists Then
// Be aware that TextInputStream.Open could raise an exception
Var t As TextInputStream
Try
t = TextInputStream.Open(f)
t.Encoding = Encodings.MacRoman
TextArea1.Value = t.ReadAll
Catch e As IOException
MessageBox("Error accessing file.")
End Try
t.Close
End If
End If
This is from a documentation example. Of course, you have to change some things for your project. Probably, setting encodings to UTF8, or the file name accordingly.
No, that ain’t safe anymore. According to Apple, if you use macOS.
Is that really from the docs? I’ve removed the 2 nested ifs. Without the nesting the code is easier to read:
Var f As FolderItem = FolderItem.ShowOpenFileDialog("text") // as defined in File Type Sets Editor
If f = Nil or not f.exists Then return
// Be aware that TextInputStream.Open could raise an exception
Var t As TextInputStream
Try
t = TextInputStream.Open(f)
t.Encoding = Encodings.MacRoman
TextArea1.Value = t.ReadAll
t.Close
Catch e As IOException
MessageBox("Error accessing file.")
End Try
t.close must be in the try/catch. If there is an exception t might be nil and closing the TextInputStream would make a NilObjectException.
you can add a build step copy files to windows build settings (context menu)
with target to ressources folder.
drag & drop your file into.
than you load this file at runtime
Var f As FolderItem = SpecialFolder.Resources.Child("file.txt")
Var st As TextInputStream = TextInputStream.Open(f)
TextArea1.Text = st.ReadAll
st.Close