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
 

rworner

Member
Licensed User
Longtime User
I am developing for a rooted MK802 mini PC. I have created a local.prop file that I can manually instal via a file manager, but want to automate the process using the code below.

WhenI run this I get the following error:
FileNotFoundException: /data/local.prop open failed EACCES (Permission Denied)
-----------------------------

Sub Globals
Dim tw As TextWriter
End Sub
Sub Activity_Create(FirstTime As Boolean)

Dim s1, sr1, sr2, sr3 As String
s1="local.prop"
sr1="service.adb.tcp.port=5555"
sr2="ro.kernel.android.bootanim=0"
sr3="debug.sf.nobootanimation=1"
If File.Exists("/data/",s1)= False Then
tw.Initialize(File.OpenOutput("/data/",s1,False))
tw.WriteLine(sr1)
tw.WriteLine(sr2)
tw.WriteLine(sr3)
tw.Close
End If
End Sub
 

eps

Expert
Licensed User
Longtime User
Ideally you should start a new thread for a Q like this, but to try and help the problem is the location of the file, you need
to tell it where it is, it should be located under the directories that form part of your App, such as :

B4X:
TextWriteLine.Initialize(File.OpenOutput(File.DirInternal, "yourfile.txt", False))

I think it would be best to use the DirInternal, then prepend the /data/ part to your file name..

HTH
 

rworner

Member
Licensed User
Longtime User
Tr
Ideally you should start a new thread for a Q like this, but to try and help the problem is the location of the file, you need
to tell it where it is, it should be located under the directories that form part of your App, such as :

B4X:
TextWriteLine.Initialize(File.OpenOutput(File.DirInternal, "yourfile.txt", False))

I think it would be best to use the DirInternal, then prepend the /data/ part to your file name..

HTH

I tried the suggestion, no luck.
I also tried a SU account --but instead of creating /data/local.prop it created /<packagename>/local.prop

Sub Activity_Create(FirstTime As Boolean)

Dim Command, Runner As String
Dim StdOut, StdErr As StringBuilder
Dim Result As Int
Dim Ph As Phone
StdOut.Initialize
StdErr.Initialize
Runner = File.Combine(File.DirInternal, "runner")
Command = File.Combine(File.DirInternal, "command")
File.WriteString(File.DirInternalCache, "runner", "su < " & Command)
File.WriteString(File.DirInternalCache, "command", "echo service.adb.tcp.port=5555 >> /data/local.prop" & CRLF & "exit") 'Any commands via crlf, and exit at end
Result = Ph.Shell("sh", Array As String(Runner), StdOut, StdErr)
Log("Result: " & Result)
Runner = File.Combine(File.DirInternal, "runner")
Command = File.Combine(File.DirInternal, "command")
File.WriteString(File.DirInternalCache, "runner", "su < " & Command)
File.WriteString(File.DirInternalCache, "command", "echo ro.kernel.android.bootanim=0 >> /data/local.prop" & CRLF & "exit") 'Any commands via crlf, and exit at end
Result = Ph.Shell("sh", Array As String(Runner), StdOut, StdErr)
Log("Result: " & Result)
Runner = File.Combine(File.DirInternal, "runner")
Command = File.Combine(File.DirInternal, "command")
File.WriteString(File.DirInternalCache, "runner", "su < " & Command)
File.WriteString(File.DirInternalCache, "command", "echo debug.sf.nobootanimation=1 >> /data/local.prop" & CRLF & "exit") 'Any commands via crlf, and exit at end
Result = Ph.Shell("sh", Array As String(Runner), StdOut, StdErr)
Log("Result: " & Result)
End Sub
 

eps

Expert
Licensed User
Longtime User
I can't see in your code where it carries out the FileOpen part...??

Can you enclose the above in
"[ code ]"

"[ /code ]"

tags please?
 

djveleno

Active Member
Licensed User
Longtime User
Hi Sarah,
There is an example here: add imageview half manually

The program loads image files from a folder and shows them in a ScrollView with ImageViews.
In the code you should either choose the right code line for the folder you want or change one line with your folder.
B4X:
[FONT=Courier New][SIZE=2][FONT=Courier New][SIZE=2]bmpImage.Initialize([/SIZE][/FONT][COLOR=#0000ff][FONT=Courier New][SIZE=2][COLOR=#0000ff][FONT=Courier New][SIZE=2][COLOR=#0000ff]File[/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT][/COLOR][FONT=Courier New][SIZE=2].DirAssets,[/SIZE][/FONT][COLOR=#800000][FONT=Courier New][SIZE=2][COLOR=#800000][FONT=Courier New][SIZE=2][COLOR=#800000]"Image"[/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT][/COLOR][FONT=Courier New][SIZE=2]&i&[/SIZE][/FONT][COLOR=#800000][FONT=Courier New][SIZE=2][COLOR=#800000][FONT=Courier New][SIZE=2][COLOR=#800000]".jpg"[/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT][/COLOR][FONT=Courier New][SIZE=2])[/SIZE][/FONT]
[COLOR=#008000][FONT=Courier New][SIZE=2][COLOR=#008000][FONT=Courier New][SIZE=2][COLOR=#008000]' bmpImage.Initialize(File.DirInternal,"Image"&i&".jpg")[/COLOR][/SIZE][/FONT]
[SIZE=2][FONT=Courier New][COLOR=#008000]' bmpImage.Initialize(File.DirDefaultExternal,"Image"&i&".jpg")[/COLOR][/FONT][/SIZE][/COLOR][/SIZE][/FONT][/COLOR][/SIZE][/FONT]
The default folder is in the program is File.DirAssets.

Best regards.
Hi Klaus,
I created an app that has many pictures in different folders, how can I load images from these folders?
I used this code, but it does not work:
B4X:
ImageView1.Bitmap = LoadBitmap(File.DirAssets &/"automibili", ImageFiles(0))
Thanks for all.
 

klaus

Expert
Licensed User
Longtime User
Unfortunately you don't give enough information to help you !
What have you done, don't you have a project showing the problem.
What doesn't work ?
Do you get any error messages ?
Does the folder File.DirAssets &/"automibili" exist ?
What is ImageFiles(0) and how is it defined ?
Well, it's almost impossible to help whithout knowing the answeres to these questions !
The best way : post your project as a zip file (IDE menu File / Export As Zip) so we could see what you have done and how and test your project in the same conditions as you do.

Best regards.
 

dieterp

Active Member
Licensed User
Longtime User
I use a List to store a recordset using the DBUtils.ExecuteMemoryTable function. When I use File.WriteList to write that List to a text file, it writes the actual arraytype ([Ljava.lang.String;@42397b68) and not the entries I retrieve from the database. Is it possible to write a recordset that would have several rows containing Name, Surname, Age etc. values to a text file?
 

IslamQabel

Active Member
Licensed User
Longtime User
Thanks Erel, very helpful......So i made a code that i can read the help from a files stored in "Files" folder instead typing a very long help in Msgbox..
B4X:
sub Activity_Create

Activity.AddMenuItem("HELP","MenuHelp")
End Sub


Sub MenuHelp_click
    Msgbox(File.ReadString(File.DirAssets, "help.txt"), "Help")
End Sub

Can i display the contents of a txt file in Msgbox with different color , different font and change the color of background ?
 

Kwame Twum

Active Member
Licensed User
Longtime User
Please guys, how do you read a text file from a remote computer/server?
 

agus mulyana

Member
Licensed User
Longtime User
Dear all

Execuse me, I want to open an EXCEL file (ex: boox1 from SD Card) , anyone can help me ? or give me a free sample/code for this ? thank you
 

schemer

Active Member
Licensed User
Longtime User
I have found this page and am trying to test it for saving a text file. The demo from page one seems to work until it gets to the last two subroutines and the screen goes blank. What is supposed to happen there and how do I access the file on my device? Here are the last two subs:

B4X:
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

Thanks,
schemer

edit: I think I see the answer: 'write the line to LogCat :)
 

schemer

Active Member
Licensed User
Longtime User
Note that in most cases there is no reason to use TextReader and TextWriter. You should instead use File.WriteString or WriteList (and ReadString, ReadList).

Thank you Erel for the added info. I will do some more studying. My Nexus 7 arrives today so I will have a dedicated test device. WooHoo! :p
schemer
 

haddad

Member
Licensed User
Longtime User
hi all
i have a problemme i can write in a file txt but can't read it , may i have a permission for reading or what ?

cordialement
 
Top