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
 

Jim Brown

Active Member
Licensed User
Longtime User
Erel,


Before I get going on my next project I would like to know whether any data stored in the persistent storage area is destroyed each time you update your app?

If so, is there a good method to prevent this from happening? I know a lot of apps downloaded from the market can be safely updated without destroying the current data

Is it just a matter of saving data to the external sd card only?
 

James Moxham

Member
Licensed User
Longtime User
This is a great little tute.

I was wondering if I could ask for some help reading and writing binary files. This is a very simple bit of vb.net code. Maybe a bit old-school but it is still valid code and about as simple as you can get.
B4X:
        FileOpen(1, "C:\Test.bin", OpenMode.Binary) ' open a file
        FilePut(1, 65) ' store an "A"
        FileClose(1) ' close the file

What would be the equivalent in Basic4Android?

I got as far as finding "openoutput". And based on a bit of code I found elsewhere, saving to the sd card might aid in debugging so I tried this
B4X:
   OpenOutput("/sdcard","Testfile.txt",False) As OutputStream

Is the "/sdcard" going to write to the sd card?
Do I need to put some data in an outputstream (? an array) prior to writing it?
How do you close the file?

Help would be most appreciated!
 
Last edited:

Cableguy

Expert
Licensed User
Longtime User
I need to read from and write to a file, but I need that file to be already existing upon first run, so I have created a template file...but how do I add this file to my project and were's the best place to keep it, I do not want to access the SD...it's just a 1kb text file...

HELP!?
 
Last edited:

Cableguy

Expert
Licensed User
Longtime User
Thanks Erel
 

Cableguy

Expert
Licensed User
Longtime User
Small typo in the code:

B4X:
If FirstTime Then
 If File.Exist[B][COLOR="Red"]s[/COLOR][/B](File.DirInternal, "yourfile") = False Then
   File.Copy(File.DirAssets, "yourfile", File.DirInternal, "yourfile")
 End If
End If
 

Cableguy

Expert
Licensed User
Longtime User
This code does nothing:

B4X:
File.WriteString(File.DirInternal,"Score.txt",TotalScore)
And the context help is missing(?) the value parameter...
So, how do I write a value to a file? This file is non existing, and does not get created...
 
Last edited:

Cableguy

Expert
Licensed User
Longtime User
I see the typo in the context help. It will be fixed.

Your code looks correct. Target the sd card instead to see the file.

The code is in fact correct and targeting the SD card I can see the file...But DirInternal should be Read/write enables right?
I can copy files to it from assets, but canot create new one?
Is it a time delay issue or permitions?
 

Cableguy

Expert
Licensed User
Longtime User
You can write to File.DirInternal. It is just harder to debug.

Are you closing the file before trying to read it?

No I am Not...I was not aware of the need for it...
I've managed to read and write a file to DirInternal....must have been something in my code...
 

SarahWard

Banned
Using images from SD-CARD or external source

Has anyone got a demo program that would show me how to:

1. load an image (jpg) from an external source (i.e. SD CARD)

2. Display an image (jpg) on the Android screen?

Most of the tutorials seem to be about web-based activity rather than the events surrounding non-web applications requirements and I am finding it hard to get a .b4a source that can demonstrate these basic hardware based things

I need to load an image from the SD CARD source.

Any help would be appreciated.

Sarah:sign0104:
 
Top