How to create a text file and write and then read from it?

Hello all,

I don’t do much with file handling, so I’m a little stumped by how to create a file in the folder that the app is in. Following creation, I want to write to it, then read what was written.

Anyone have sample code to do this?
Thanks,
Tim

I got this. Will post code later for others who may have hit a bump also,
Tim

I used the ApplicationData folder instead of the current app folder because most of the time in a deployed app you will not have write permissions to that folder.

Var appFolder As FolderItem = SpecialFolder.ApplicationData
Var textFile As FolderItem = appFolder.Child("Hello.txt")

// Write "HELLO" to the text file
Var textOutputStream As TextOutputStream
Try
  textOutputStream = TextOutputStream.Open(textFile)
  textOutputStream.Write("HELLO")
Catch e As IOException
  MessageBox("Error writing to file.")
Finally
  textOutputStream.Close
End Try

// Read the content back from the file
Var textInputStream As TextInputStream
Var content As String
Try
textInputStream = TextInputStream.Open(textFile)
content = textInputStream.ReadAll
Catch e As IOException
  MessageBox("Error reading from file.")
Finally
  textInputStream.Close
End Try
// Display the content in a MessageBox
MessageBox(content)

Thank you!
Tim

Here is an example of a method I use to write to a text log file. The file name is good until the date changes and then a new log file gets started when the next log transaction request is processed. Log files are stored in the “application folder/Logs” folder. Usage is

LogTransactions("your text goes here")
Public Sub LogTransactions(logentry As String)
  Var logfldr,logfile As FolderItem
  Var tos as TextOutputStream
  Var d As Date = New Date
  Var currentlog,logstring As String
  
  currentlog = Str(d.Year) + "-" + Str(d.Month) + "-" + Str(d.Day) + "_" + App.kAppShortName + "_transaction.log"
  logstring = d.SQLDateTime + Chr(9) + logentry
  
  logfldr = GetFolderItem("Logs")
  
  If Not (logfldr = Nil) Then
    If Not logfldr.Exists Then
      logfldr.CreateAsFolder
    End If
  End If
  
  logfile = logfldr.Child(currentlog)
  
  If Not (logfile = Nil) Then
    If logfile.Exists Then
      tos = TextOutputStream.Append(logfile)
      tos.WriteLine(logstring)
      tos.Close
    Else
      tos = TextOutputStream.Create(logfile)
      tos.WriteLine(d.SQLDateTime + Chr(9) + App.kAppLongName + " Transaction Log Created")
      tos.WriteLine("***********************************************************************************************************************************************************")
      tos.WriteLine(logstring)
      tos.Close
    End If
  End If
  
End Sub