[Java] [Android] Read ini file

00. Introduction

One way to save the settings to a file in Java is to save it as a .properties file. However, there are times when you want to use an .ini file, such as recreating an app created in C ++ in Java (or rather, during this time). So, let's write a process to read it.

01. About the .ini file to be read

It seems that .ini files do not have a strict format, so this time we will target the following formats.

  1. ** Comment line **
    Ignore lines starting with'#' as comment lines.
    It is not possible to start a comment in the middle of a sentence.
  2. ** Section line **
    Lines that start with'['and end with']' are considered section lines, and the enclosed string is a section.
    Subsequent parameters found shall belong to this section.
  3. ** Parameter line **
    The line with'=' in the sentence is the parameter line, the left side that first appears is the key, and the right side is the value.
  4. ** Other than the above **
    ignore

02. Here is the finished product.

IniFileLoader.java


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 *Loader to load IniFile
 */
public class IniFileLoader {
    // HashMap<section, HashMap<key, String>>To
    private HashMap<String, HashMap<String, String>> mDataMap;

    //File Path
    private String mFilePath;

    //Is load completed?
    private boolean mIsLoaded = false;

    /**
     *Load the specified file
     *
     * @param filePath File path
     * @return Whether the load was successful
     */
    public boolean load(String filePath) {
        mFilePath = filePath;
        return loadProcess(filePath);
    }

    /**
     *Reload the file you last tried to load
     *
     * @return Whether the load was successful
     */
    public boolean reload() {
        return isEmpty(mFilePath) && loadProcess(mFilePath);
    }

    private boolean loadProcess(String filePath) {
        mIsLoaded = false;
        mDataMap = new HashMap<>();
        try {
            FileReader fileReader = new FileReader(new File(filePath));
            BufferedReader br = new BufferedReader(fileReader);
            String line = br.readLine();

            //Section name
            String section = null;
            //Key value
            HashMap<String, String> map = new HashMap<>();
            while (line != null) {
                //Remove whitespace at the beginning and end of lines
                line = line.trim();

                //Blank line
                if (isEmpty(line)) {
                    // no process
                }
                //Comment line
                else if (line.charAt(0) == '#') {
                    // no process
                }
                //Section line
                else if (line.charAt(0) == '[' && line.charAt(line.length() - 1) == ']') {
                    section = line.substring(1, line.length() - 1);
                    map = new HashMap<>();
                }
                //Parameter line
                else if (line.length() >= 3 && line.contains("=") && line.length() > line.indexOf("=") + 1) {
                    String key = line.substring(0, line.indexOf("="));
                    String value = line.substring(line.indexOf("=") + 1);

                    map.put(key, value);
                    mDataMap.put(section, map);
                }

                line = br.readLine();
            }
            br.close();
        } catch (IOException e) {
            return false;
        }
        mIsLoaded = true;
        return true;
    }

    /**
     *Read the result(section, (key, value))of{@link HashMap}Return with
     *
     * @return The result of reading{@link HashMap} 
     */
    public HashMap<String, HashMap<String, IniItem>> getAllDataMap() {
        if (mIsLoaded) {
            return mDataMap;
        }
        return null;
    }

    /**
     *The specified section of the read result(key, value)of{@link Map}Return with
     *
     * @param section Section specification
     * @return The specified section of the read result
     */
    public Map<String, String> getSectionDataMap(String section) {
        if (mIsLoaded) {
            return mDataMap.get(section);
        }
        return null;
    }

    /**
     *Returns the value of the specified section, specified key
     *
     * @param section Section specification
     * @param key key specification
     * @return Specified section, specified key value
     */
    public String getValue(String section, String key) {
        if (mIsLoaded) {
            HashMap<String, String> map = mDataMap.get(section);
            if (map != null) {
                return map.get(key);
            }
        }
        return null;
    }

    /**
     *Returns whether the specified section is in the read result
     *
     * @param section Section specification
     * @return if it exists{@code true}
     */
    public boolean containsSection(String section) {
        if (mIsLoaded) {
            return mDataMap.containsKey(section);
        }
        return false;
    }

    /**
     *Returns whether the specified key in the specified section is in the read result
     *
     * @param section Section specification
     * @param key key specification
     * @return if it exists{@code true}
     */
    public boolean containsKey(String section, String key) {
        if (mIsLoaded) {
            HashMap<String, IniItem> map = mDataMap.get(section);
            return map != null && map.containsKey(key);
        }
        return false;
    }

    /**
     * {@code String}Determine if is empty
     *
     * @param str Judgment target
     * @return {@code String}If is empty{@code true}
     */
    private boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }
}

You just read it line by line and make a judgment.

03. Here is what I made into a library.

https://github.com/entan05/IniFileController

I made it into a library. For the time being, it can also be used on Android.

98. Reference

[Java] [Sample code] I made my own INI file read / write library | http://javasampleokiba.blog.fc2.com/blog-entry-27.html

99. Update history

date Contents
2018/03/24 Post

Recommended Posts

[Java] [Android] Read ini file
Read Java Property file
Read Java properties file in C #
java file creation
Read xlsx file in Java with Selenium
Read a string in a PDF file with Java
[Java] Read the file in src / main / resources
[Java] File system operation
Read JSON in Java
java (split source file)
java core: chopped core file
Read Java HashMap source
<java> Read Zip file and convert directly to string
How to read your own YAML file (*****. Yml) in Java
Read binary files in Java 1
Edit ini in Java: ini4j
Read WAV data as a byte array in Android Java
[Java] Create a temporary file
Read binary files in Java 2
Java beginners read Hello World
[Android / Java] Learned about DataBinding
Text file placed in resources in Java cannot be read when jarted
Read the first 4 bytes of the Java class file and output CAFEBABE
Read items containing commas in a CSV file without splitting (Java)
Sample to read and write LibreOffice Calc fods file in Java 2021
Read and generate QR code [Android]
Try implementing Android Hilt in Java
Easy implementation of Android file browsing
Upload a file using Java HttpURLConnection
Read CSV in Java (Super CSV Annotation)
Run node.js from android java (processing)
Read dump file with Docker MySQL
Run a batch file from Java
Unzip the zip file in Java
[Android Studio] [Java] Learning memos & links
Log output to file in Java
EXCEL file update sample with JAVA
About file copy processing in Java
Notes on Android (java) thread processing
Reintroducing Java 8 available from Android Studio 2.4
[Android] Convert Android Java code to Kotlin
How to read log4j configuration file in Java project summarized in jar file Memo