Android Tutorial Text files

Discussion in 'Tutorials & Examples' started by Erel, Nov 28, 2010.

  1. Erel

    Erel Administrator Staff Member Licensed User

    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.

    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.

    The storage card root folder.

    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.

    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.""")
    End If
    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
    For i = 1 To 100
    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
    For i = 1 To 10
    "Key" & i, "Value" & i)
    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
    "The map entries are:").Append(CRLF)
    For i = 0 To Map1.Size - 1
    "Key = ").Append(Map1.GetKeyAt(i)).Append(", Value = ")
    End Sub

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

    Sub ReadTextReader
    Dim TextReader1 As TextReader
    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
    End Sub
  2. ashrafidkaidek

    ashrafidkaidek Member Licensed User

  3. Erel

    Erel Administrator Staff Member Licensed User

    File.WriteList expects a List object not a ListView object.
  4. ashrafidkaidek

    ashrafidkaidek Member Licensed User

    Thank you Erel
  5. Jim Brown

    Jim Brown Active Member Licensed User


    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?
  6. Erel

    Erel Administrator Staff Member Licensed User

    No data is erased during update. Only when the user uninstalls your application.
    TedDog likes this.
  7. Jim Brown

    Jim Brown Active Member Licensed User

    That's terrific news. Thanks
  8. James Moxham

    James Moxham Member Licensed 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 code. Maybe a bit old-school but it is still valid code and about as simple as you can get.
    FileOpen(1"C:\Test.bin", OpenMode.Binary) ' open a file
            FilePut(165' 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
    OpenOutput("/sdcard","Testfile.txt",FalseAs 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: Jan 24, 2011
  9. Erel

    Erel Administrator Staff Member Licensed User

    RobyLaga likes this.
  10. James Moxham

    James Moxham Member Licensed User

    Brilliant! Thanks Erel.
  11. Cableguy

    Cableguy Expert Licensed 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's just a 1kb text file...

    Last edited: Jan 30, 2011
  12. Erel

    Erel Administrator Staff Member Licensed User

    Add the file to the Files tab.
    Then in Activity_Create:
    If FirstTime Then
    If File.Exist(File.DirInternal, "yourfile") = False Then
    File.Copy(File.DirAssets, "yourfile"File.DirInternal, "yourfile")
    End If
    End If
    RobyLaga likes this.
  13. Cableguy

    Cableguy Expert Licensed User

    Thanks Erel
  14. Cableguy

    Cableguy Expert Licensed User

    Small typo in the code:

    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
  15. Cableguy

    Cableguy Expert Licensed User

    This code does nothing:

    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: Jan 30, 2011
  16. Erel

    Erel Administrator Staff Member Licensed 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.
  17. Cableguy

    Cableguy Expert Licensed User

    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?
  18. Erel

    Erel Administrator Staff Member Licensed User

    You can write to File.DirInternal. It is just harder to debug.

    Are you closing the file before trying to read it?
  19. Cableguy

    Cableguy Expert Licensed User

    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...
  20. SarahWard

    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.

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice