Android读写ini配置文件

目录

ini文件介绍:

不带session和注释的ini文件:

保存在内部存储上的ini文件

使用:

保存在SD卡上的ini文件

使用:

带session和注释的ini文件:

保存在内部存储上的ini文件

使用:

保存在SD卡上的ini文件

使用:


ini文件介绍:

; bashful
[bashful]
weight = 45.7
height = 98.8
age = 67
homePage = http://snowwhite.tale/~bashful
homeDir = /home/bashful

; doc
[doc]
weight = 49.5
height = 87.7
age = 63
homePage = http://doc.dwarfs
homeDir = c:\Documents and Settings\doc

在该文件中有三种数据:

1. ; bashful 像这种  ;  表示该行是注释,符号后面表示注释的内容

2. [bashful] 像这种 [ ]里面的就是session

3. 后面=两边表示的是键值对存储的数据,左边的是key,右边的是value

不带session和注释的ini文件:

文件保存的数据只有键值对形式

weight = 45.7

height = 98.8 age = 67

homePage = http://snowwhite.tale/~bashful

homeDir = /home/bashful

保存在内部存储上的ini文件

public class InternalConfigure {
    private final Context context;
    private Properties properties;

    public InternalConfigure(Context context) {
        super();
        this.context = context;
    }

    /**
     * 保存文件filename为文件名,filecontent为存入的文件内容
     * 例:configureActivity.saveFiletoSD("text.ini","");
     */
    public void saveFile(String filename, Properties properties) throws Exception {
        //设置Context.MODE_PRIVATE表示每次调用该方法会覆盖原来的文件数据
        FileOutputStream fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
        //通过properties.stringPropertyNames()获得所有key的集合Set,里面是String对象
        for (String key : properties.stringPropertyNames()) {
            String s = key + " = " + properties.getProperty(key) + "\n";
            System.out.println(s);
            fileOutputStream.write(s.getBytes());
        }
        fileOutputStream.close();
    }

    /**
     * 读取文件
     */
    public void readFrom(String filename) throws Exception {
        properties = new Properties();

        FileInputStream fileInputStream = context.openFileInput(filename);
        properties.load(fileInputStream);
        fileInputStream.close();
    }

    /**
     * 返回指定key对应的value
     */
    public String getIniKey(String key) {
        if (properties.containsKey(key) == false) {
            return null;
        }
        return String.valueOf(properties.get(key));
    }
}

使用:

            //写
            InternalConfigure internalConfigure=new InternalConfigure(this);
            Properties properties=new Properties();
            properties.put("textsize",String.valueOf(textView.getTextSize()));
            properties.put("textcolor",String.valueOf(textView.getTextColors().getDefaultColor()));
            properties.put("backgroundcolor",String.valueOf(dra.getColor()));
            internalConfigure.saveFile("text.ini",properties);
            //读
            InternalConfigure internalConfigure=new InternalConfigure(this);
            internalConfigure.readFrom("text.ini");
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,Float.parseFloat(String.valueOf(internalConfigure.getIniKey("textsize"))));
            textView.setBackgroundColor(Integer.parseInt(String.valueOf(internalConfigure.getIniKey("backgroundcolor"))));
            textView.setTextColor(Integer.parseInt(String.valueOf(internalConfigure.getIniKey("textcolor"))));

保存在SD卡上的ini文件

public class ConfigureActivity {
    private final Context context;
    private  Properties properties;
    public ConfigureActivity(Context context){
        super();
        this.context=context;
    }
    /**
     * 保存文件filename为文件名,filecontent为存入的Properties对象
     * 例:configureActivity.saveFiletoSD("text.ini",properties);
     */
    public void saveFiletoSD(String filename,Properties properties)throws Exception{
        //if条件判定SD卡是否存在并具有读写权限
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            filename=Environment.getExternalStorageDirectory().getCanonicalPath()+"/"+filename;
            //FileOutputStream()里面直接添加filename会覆盖原来的文件数据
            FileOutputStream fileOutputStream=new FileOutputStream(filename);
           //通过properties.stringPropertyNames()获得所有key的集合Set,里面是String对象
            for(String key : properties.stringPropertyNames()){
                String s=key+" = "+properties.getProperty(key)+"\n";
                System.out.println(s);
                fileOutputStream.write(s.getBytes());
            }

            fileOutputStream.close();
        }else {
            Toast.makeText(context,"写入错误",Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 读取文件
     * */
    public void readFromSD(String filename)throws Exception{
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            properties = new Properties();
            filename=Environment.getExternalStorageDirectory().getCanonicalPath()+"/"+filename;
            FileInputStream fileInputStream=new FileInputStream(filename);
            properties.load(fileInputStream);
            fileInputStream.close();
        }else {
            Toast.makeText(context,"读取错误",Toast.LENGTH_SHORT).show();
        }
    }
    public String getIniKey(String key) {
        if (properties.containsKey(key) == false) {
            return null;
        }
        return String.valueOf(properties.get(key));
    }
}

使用:

            //存
            ConfigureActivity configureActivity=new ConfigureActivity(this);
            Properties properties=new Properties();
            properties.put("textsize",String.valueOf(textView.getTextSize()));
            properties.put("textcolor",String.valueOf(textView.getTextColors().getDefaultColor()));
            properties.put("backgroundcolor",String.valueOf(dra.getColor()));
            configureActivity.saveFiletoSD("text.ini",properties);
            //取
            ConfigureActivity configureActivity=new ConfigureActivity(this);
            configureActivity.readFromSD("text.ini");
            configureActivity.getIniKey("textsize");
            configureActivity.getIniKey("backgroundcolor");
            configureActivity.getIniKey("textcolor");

带session和注释的ini文件:

保存在内部存储上的ini文件

public class InternalConfigure {
    private final Context context;
    private Properties properties;
    private HashMap<String,Properties> sessions;
    public InternalConfigure(Context context) {
        super();
        this.context = context;
    }

    /**
     * 保存文件filename为文件名,session为一组HashMap集合,notes为注释
     */
    public void saveFile(String filename, HashMap<String,Properties> session,String notes) throws Exception {
        //设置Context.MODE_PRIVATE表示每次调用该方法会覆盖原来的文件数据
        FileOutputStream fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
        //keySet()方法
        Set<String> keySet = session.keySet(); //获取map集合所有键的Set()集合(于集合中无序存放)
        Iterator<String> iterator = keySet.iterator(); //获取keySet集合的迭代器
        notes=";"+notes+"\n";
        fileOutputStream.write(notes.getBytes());
        while(iterator.hasNext()) {
            //获取key值
            String sessionkey = iterator.next();
            String sa="["+sessionkey+"]"+"\n";
            fileOutputStream.write(sa.getBytes());
            //遍历properties
            for (String key : Objects.requireNonNull(session.get(sessionkey)).stringPropertyNames()) {
                String s = key + " = " + Objects.requireNonNull(session.get(sessionkey)).getProperty(key) + "\n";
                System.out.println(s);
                fileOutputStream.write(s.getBytes());
            }
        }
        fileOutputStream.close();
    }

    /**
     * 读取文件
     */
    public void readFrom(String filename) throws Exception {
        sessions=new HashMap<>();
        FileInputStream fileInputStream = context.openFileInput(filename);
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            parseLine(line);
        }
        fileInputStream.close();
    }
    //判断文件行类型并写入session中
    private void parseLine(String line) {
        //去除字符串的头尾空格
        line = line.trim();
        if (line.matches("\\[.*\\]")) {
            String section = line.replaceFirst("\\[(.*)\\]", "$1");
            properties = new Properties();
            sessions.put(section, properties);
        } else if (line.matches(".*=.*")) {

            if (properties != null) {
                int i = line.indexOf('=');
                String name = line.substring(0, i).trim();
                String value = line.substring(i + 1).trim();
                properties.put(name, value);
            }
        }
    }


    /**
     * 返回指定key对应的value
     */
    public String getIniKey(String key,String session) {
        if (!sessions.containsKey(session)){
            return null;
        }else {
            if (!sessions.get(session).containsKey(key)){
                return null;
            }else {
                return String.valueOf(Objects.requireNonNull(sessions.get(session)).get(key));
            }
        }


    }
    
}

使用:

            //取
            InternalConfigure internalConfigure=new InternalConfigure(this);
            internalConfigure.readFrom("text.ini");
            internalConfigure.getIniKey("textsize","textview");
            internalConfigure.getIniKey("backgroundcolor","textview");
            internalConfigure.getIniKey("textcolor","textview");

            //存
            InternalConfigure internalConfigure=new InternalConfigure(this);
            HashMap<String,Properties> sessions=new HashMap<>();
            Properties properties=new Properties();
            properties.put("textsize",String.valueOf(textView.getTextSize()));
            properties.put("textcolor",String.valueOf(textView.getTextColors().getDefaultColor()));
            properties.put("backgroundcolor",String.valueOf(dra.getColor()));
            sessions.put("textview",properties);
            internalConfigure.saveFile("text.ini",sessions,"文本属性");

保存在SD卡上的ini文件

public class ConfigureActivity {
    private final Context context;
    private Properties properties;
    private HashMap<String,Properties> sessions;
    public ConfigureActivity(Context context){
        super();
        this.context=context;
    }
    /**
     * 保存文件filename为文件名,session为一组HashMap集合,notes为注释
     */
    public void saveFiletoSD(String filename, HashMap<String,Properties> session, String notes)throws Exception {
        //if条件判定SD卡是否存在并具有读写权限
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            filename = Environment.getExternalStorageDirectory().getCanonicalPath() + "/" + filename;
            //FileOutputStream()里面直接添加filename会覆盖原来的文件数据
            FileOutputStream fileOutputStream = new FileOutputStream(filename);
            //keySet()方法
            Set<String> keySet = session.keySet(); //获取map集合所有键的Set()集合(于集合中无序存放)
            Iterator<String> iterator = keySet.iterator(); //获取keySet集合的迭代器
            notes = ";" + notes + "\n";
            fileOutputStream.write(notes.getBytes());
            while (iterator.hasNext()) {
                //获取key值
                String sessionkey = iterator.next();
                String sa = "[" + sessionkey + "]" + "\n";
                fileOutputStream.write(sa.getBytes());
                //遍历properties
                for (String key : Objects.requireNonNull(session.get(sessionkey)).stringPropertyNames()) {
                    String s = key + " = " + Objects.requireNonNull(session.get(sessionkey)).getProperty(key) + "\n";
                    System.out.println(s);
                    fileOutputStream.write(s.getBytes());
                }
            }
            fileOutputStream.close();
        }
    }

    /**
     * 读取文件
     * */
    public void readFromSD(String filename)throws Exception {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                filename = Environment.getExternalStorageDirectory().getCanonicalPath() + "/" + filename;
                sessions = new HashMap<>();
                FileInputStream fileInputStream=new FileInputStream(filename);
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    parseLine(line);
                }
                fileInputStream.close();
            }
        }
    //判断文件行类型并写入session中
    private void parseLine(String line) {
        //去除字符串的头尾空格
        line = line.trim();
        if (line.matches("\\[.*\\]")) {
            String section = line.replaceFirst("\\[(.*)\\]", "$1");
            properties = new Properties();
            sessions.put(section, properties);
        } else if (line.matches(".*=.*")) {

            if (properties != null) {
                int i = line.indexOf('=');
                String name = line.substring(0, i).trim();
                String value = line.substring(i + 1).trim();
                properties.put(name, value);
            }
        }
    }


    /**
     * 返回指定key对应的value
     */
    public String getIniKey(String key,String session) {
        if (!sessions.containsKey(session)){
            return null;
        }else {
            if (!sessions.get(session).containsKey(key)){
                return null;
            }else {
                return String.valueOf(Objects.requireNonNull(sessions.get(session)).get(key));
            }
        }


    }
}

使用:

            //读
            ConfigureActivity configureActivity=new ConfigureActivity(this);
            configureActivity.readFromSD("text.ini");
            configureActivity.getIniKey("textsize","textview");
            configureActivity.getIniKey("backgroundcolor","textview");
            configureActivity.getIniKey("textcolor","textview");
            //写
            ConfigureActivity configureActivity=new ConfigureActivity(this);
            HashMap<String,Properties> sessions=new HashMap<>();
            Properties properties=new Properties();
            properties.put("textsize",String.valueOf(textView.getTextSize()));
            properties.put("textcolor",String.valueOf(textView.getTextColors().getDefaultColor()));
            properties.put("backgroundcolor",String.valueOf(dra.getColor()));
            sessions.put("textview",properties);
            configureActivity.saveFiletoSD("text.ini",sessions,"文本属性");

  • 7
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在Linux中,可以使用各种方法来读写INI配置文件。 首先,INI配置文件通常采用文本格式,可以使用文本编辑器(如vi、nano等)直接编辑配置文件。你可以通过打开终端,进入配置文件所在的目录,使用文本编辑器打开配置文件,进行修改和保存。 其次,Linux提供了一些命令行工具来处理INI配置文件,如sed和awk。sed是流编辑器,可以用来处理和修改文本文件。通过使用sed命令,你可以根据需要修改INI配置文件中的特定键和值。类似地,awk也可用于处理INI配置文件,它是一种强大的文本处理工具,具有高级的文本处理功能。 此外,你还可以通过编写脚本来读写INI配置文件,如使用bash脚本、Python脚本等。通过读取配置文件,并解析其中的键值对,你可以在脚本中直接使用这些配置参数。在脚本中,你可以使用文本处理函数、正则表达式等工具来解析和修改INI配置文件。 最后,还有一些特定的库和工具可以用于读写INI配置文件,如Python中的configparser模块。这些库和工具提供了更高级的功能,可以方便地读取和修改INI配置文件,同时还可以进行验证、错误处理等操作。 总之,Linux提供了多种方法用于读写INI配置文件,从简单的文本编辑器到强大的命令行工具和编程语言,你可以根据自己的需求选择适合的工具来处理INI配置文件
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值