B4J Question Read / Write an .ini-File line by line

GMan

Well-Known Member
Licensed User
Longtime User
How can i save & read-out a multiline .ini-Textfile ?
one-line files are no problem ;-)

i.e. number1.ini:

true
false
false
true

i have boolean variables that must be filled on programstart with the last settings.

When saving, each line in each .ini File (there a 16 of it) must be possible to update, i.e. number1.ini

true
true
false
true

Here only line2 changes and has to be set immediatly after switching the relay

Or in another way:
is it possible to READ the status of an relay direct from itself or works it only with this "last setting" solution ?
 

rwblinn

Well-Known Member
Licensed User
Longtime User
Hi,

consider to use a map and read & save the map (one of the great B4J features) - is easier to get or put configuration items.

Example Snippet
B4X:
' Define the global map
Sub Process_Globals
  ' Global Map holding the settings
  Public  SettingsMap As Map            
  ' Define the settings file which is read by the global settings map
  Public  SettingsFile As String = "settings.txt" 
End Sub
                              
'Check if the settings file exists, else create a new file
If File.Exists(File.DirApp, SettingsFile) Then
    SettingsMap = File.ReadMap(File.DirApp, SettingsFile)
Else
    'Create a new map and save
    SettingsMap = CreateMap ("Sortlist": "False", "ButtonTitles": "False")
    File.WriteMap(File.DirApp, SettingsFile, SettingsMap)
End If

' Get the settings from the global map.
' IMPORTANT: Use exact case for the keys
Log("Get setting...")
If SettingsMap.Get("ButtonTitles") = False Then
  btnInsert.Text = ...
End If                   

Make updates by using like SettingsMap.Put("ButtonTitles", False)

' If changes to the settings are made, save the changes to the global map
File.WriteMap(File.DirApp, SettingsFile, SettingsMap)

Example content of the settings file
#Sat Apr 12 09:24:03 CEST 2014
Sortlist=false
ButtonTitles=false
 
Upvote 0

rwblinn

Well-Known Member
Licensed User
Longtime User
In addition to Post#2, if not possible for reasons to use a map, then use a list:
Example
B4X:
Sub Process_Globals
  ...
    Private settingslist As List
End Sub

Sub AppStart (Form1 As Form, Args() As String)
...
    AppInit
...
End Sub

Sub AppInit
    ReadSettings
    'Update the second item - note the list index starts at 0
    UpdateSetting(1, True)
    SaveSettings
    ListSettings
End Sub

Sub ReadSettings
    settingslist = File.ReadList(File.dirapp,"port.ini")  
End Sub

Sub UpdateSetting(idx As Int, value As Boolean)
    settingslist.Set(idx, value)
End Sub

Sub SaveSettings
    File.WriteList(File.dirapp,"port.ini", settingslist)  
End Sub

Sub ListSettings
    For Each b As Boolean In settingslist
        Log(b)
    Next
End Sub
 
Upvote 0
Top