Download the free trial version
Basic4android Video
Features
Tutorials and manuals
Showcase
Screenshots

Go Back   Android Development Forum - Basic4android > Basic4android > Basic4android Getting started & Tutorials
Documentation Wiki Register Members List B4P Search Today's Posts Mark Forums Read

Basic4android Getting started & Tutorials Android development starts here. Please do not post questions in this sub-forum.

Text files

Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 11-28-2010, 09:16 AM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 15,689
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default 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:
Code:
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
Reply With Quote
  #2 (permalink)  
Old 12-30-2010, 02:01 AM
Junior Member
 
Join Date: Mar 2010
Posts: 28
Default

I have received this error (https://sites.google.com/site/ashandroid1/) when tried to compile my app, I don’t understands the reason why I’m getting this error. Any help
Thank you folks
Reply With Quote
  #3 (permalink)  
Old 12-30-2010, 06:31 AM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 15,689
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default

File.WriteList expects a List object not a ListView object.
Reply With Quote
  #4 (permalink)  
Old 12-30-2010, 08:02 PM
Junior Member
 
Join Date: Mar 2010
Posts: 28
Default

Thank you Erel
Reply With Quote
  #5 (permalink)  
Old 01-08-2011, 06:55 AM
Senior Member
 
Join Date: Jan 2011
Posts: 157
Default

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?
Reply With Quote
  #6 (permalink)  
Old 01-08-2011, 01:48 PM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 15,689
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default

No data is erased during update. Only when the user uninstalls your application.
Reply With Quote
  #7 (permalink)  
Old 01-08-2011, 05:45 PM
Senior Member
 
Join Date: Jan 2011
Posts: 157
Default

That's terrific news. Thanks
Reply With Quote
  #8 (permalink)  
Old 01-24-2011, 12:55 PM
Junior Member
 
Join Date: Jan 2011
Location: Adelaide, Australia
Posts: 45
Default

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.
Code:
        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
Code:
    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 by James Moxham : 01-24-2011 at 12:58 PM.
Reply With Quote
  #9 (permalink)  
Old 01-24-2011, 05:49 PM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 15,689
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default

You should use the RandomAccessFile library: Basic4android - RandomAccessFile
Reply With Quote
  #10 (permalink)  
Old 01-24-2011, 09:02 PM
Junior Member
 
Join Date: Jan 2011
Location: Adelaide, Australia
Posts: 45
Default

Brilliant! Thanks Erel.
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are On

Similar Threads
Thread Thread Starter Forum Replies Last Post
Text Files Erel Tutorials 14 04-24-2009 08:26 AM
Searching all text files in a directory tsteward Questions (Windows Mobile) 5 01-03-2009 04:08 PM
Downloadfile and text files N1c0_ds Questions (Windows Mobile) 3 10-17-2008 02:55 AM
Text editor for INI files Softselect Questions (Windows Mobile) 2 11-15-2007 06:50 AM
Dividing the code into text files... Cableguy Questions (Windows Mobile) 5 05-21-2007 03:21 PM


All times are GMT. The time now is 10:19 AM.


Powered by vBulletin® Version 3.6.12
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.3.0