Android Tutorial Text files

Many applications require access to a persistent storage. The two most common storage types are files and databases.
We will cover text files in this tutorial.

The predefined Files object has several utility methods for working with text files which are pretty easy to use.

Files locations - There are several important locations where you can read or write files.

File.DirAssets
The assets folder includes the files that were added with the file manager. These files are read-only. You can not create new files in this folder (which is actually located inside the apk file).

File.DirInternal / File.DirInternalCache
These two folders are stored in the main memory and are private to your application. Other applications cannot access these files.
The cache folder may get deleted by the OS if it needs more space.

File.DirRootExternal
The storage card root folder.

File.DirDefaultExternal
The default folder for your application in the SD card.
The folder is: <storage card>/Android/data/<package>/files/
It will be created if required.

Note that calling any of the two above properties will add the EXTERNAL_STORAGE permission to your application.

Tip: You can check if there is a storage card and whether it is available with File.ExternalReadable and File.ExternalWritable.

The predefined File object (predefined means that you do not need to declare it yourself) includes several methods for writing and reading to files.
You can also use TextReader and TextWriter to do it manually.
Note that TextReader and TextWriter are not limited to files and can work with other streams.

TextReader and TextWriter have an advantage over the File read/write methods when working with large files. The File methods read the file completely and store its content in memory. In many cases this is the most convenient solution, however if you work with large files (more than 1-2mb) you may prefer to work with TextReader or TextWriter.

File.WriteString - Writes the given text to a new file.
File.ReadString - Reads a file and returns it content as a string.
File.WriteList - Writes all values stored in a list to a file. All values are converted to string type if required. Each value will be stored in its own line.
Note that if a value contains the new line character it will saved over more than one line and when you read it, it will be read as multiple items.
File.ReadList - Reads a file and stores each line as an item in a list.
File.WriteMap - Takes a map object which holds pairs of key and value elements and stores it in a text file. The file format is known as Java Properties file: .properties - Wikipedia, the free encyclopedia
The file format is not too important unless the file is supposed to be edited manually. This format makes it easy to edit it manually.
One common usage of File.WriteMap is to save a map of "settings" to a file.
File.ReadMap - Reads a properties file and returns its key/value pairs as a Map object. Note that the order of entries returned might be different than the original order.

Example:
B4X:
Sub Process_Globals

End Sub

Sub Globals

End Sub

Sub Activity_Create(FirstTime As Boolean)
    If File.ExternalWritable = False Then
        Msgbox("Cannot write on storage card.", "")
        Return
    End If
    SaveStringExample
    ReadStringExample
    
    WriteListExample
    ReadListExample
    
    WriteMapExample
    ReadMapExample
    
    WriteTextWriter
    ReadTextReader
End Sub

Sub SaveStringExample
    File.WriteString(File.DirRootExternal, "String.txt", _
        "This is some string" & CRLF & "and this is another one.")
End Sub

Sub ReadStringExample
    Msgbox(File.ReadString(File.DirRootExternal, "String.txt"), "")
End Sub

Sub WriteListExample
    Dim List1 As List
    List1.Initialize
    For i = 1 To 100
        List1.Add(i)
    Next
    File.WriteList(File.DirRootExternal, "List.txt", List1)
End Sub

Sub ReadListExample
    Dim List1 As List
    'We are not initializing the list because it just holds the list that returns from File.ReadList
    List1 = File.ReadList(File.DirRootExternal, "List.txt")
    Msgbox("List1.Size = " & List1.Size & CRLF & "The third item is: " & List1.Get(2), "")
End Sub

Sub WriteMapExample
    Dim Map1 As Map
    Map1.Initialize
    For i = 1 To 10
        Map1.Put("Key" & i, "Value" & i)
    Next
    File.WriteMap(File.DirRootExternal, "Map.txt", Map1)
End Sub

Sub ReadMapExample
    Dim Map1 As Map
    'Again we are not initializing the map.
    Map1 = File.ReadMap(File.DirRootExternal, "Map.txt")
    'Append all entries to a string builder
    Dim sb As StringBuilder
    sb.Initialize
    sb.Append("The map entries are:").Append(CRLF)
    For i = 0 To Map1.Size - 1
        sb.Append("Key = ").Append(Map1.GetKeyAt(i)).Append(", Value = ")
        sb.Append(Map1.GetValueAt(i)).Append(CRLF)
    Next
    Msgbox(sb.ToString,"")
End Sub

Sub WriteTextWriter
    Dim TextWriter1 As TextWriter
    TextWriter1.Initialize(File.OpenOutput(File.DirRootExternal, "Text.txt", False))
    For i = 1 To 10
        TextWriter1.WriteLine("Line" & i)
    Next
    TextWriter1.Close
End Sub

Sub ReadTextReader
    Dim TextReader1 As TextReader
    TextReader1.Initialize(File.OpenInput(File.DirRootExternal, "Text.txt"))
    Dim line As String
    line = TextReader1.ReadLine    
    Do While line <> Null
        Log(line) 'write the line to LogCat
        line = TextReader1.ReadLine
    Loop
    TextReader1.Close
End Sub
 

forstp

Member
Licensed User
Longtime User
I am probably pointing out my stupidity here, having just spent hours attempting to get the file process working, it turns out windows PC search function can't find the files written by apps. All sorted now, using moborobo as a pc file manager.

Thanks for all you do Erel, You Rock, what you have built is awesome.
 
Top