Android 使用Properties文件保存软件配置信息

Properties文件保存软件配置信息,类似hashmap保存信息,key和value对应。在网上找了一个封装类,使用起来特别方便
  • 封装类ProperUtil
package com.softconfig.Utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

/**
 * Created by ${王sir} on 2017/6/23.
 * application
 */

public class ProperUtil {

    private static String FilePath = "/sdcard/.Properties/";
    private static String FileName = ".investigation_terminal.properties";
    /**
     * 得到properties配置文件中的所有配置属性
     *
     * @return Properties对象
     */
    public static String getConfigProperties(String key) {
        File mfile = new File(FilePath);
        if (!mfile.exists()) {
            mfile.mkdirs();
        }
        File mfileName = new File(FilePath+FileName);
        if (!mfileName.exists()) {
            return "";
        }
        Properties props = new Properties();
        InputStream in = null;
        try {
            in = new FileInputStream(FilePath+FileName);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        try {
            props.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String value = props.getProperty(key);
        if (value==null) {
            value="";
        }
        return value;
    }


    /**
     * 给属性文件添加属性
     *
     * @param value
     * @author qiulinhe
     * @createTime 2016年6月7日 下午1:46:53
     */
    public static void writeDateToLocalFile( String key, String value) {
        File mfile = new File(FilePath);
        if (!mfile.exists()) {
            mfile.mkdirs();
        }
        Properties p = new Properties();
        try {
            InputStream in = new FileInputStream(FilePath+FileName);
            p.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        p.put(key, value);
        OutputStream fos;
        try {
            fos = new FileOutputStream(FilePath+FileName);
            p.store(fos, null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

FilePath是文件保存路径。FileName是保存文件的名称

  • 运用
    将信息保存到文件中
Sting testContent = "测试内容";
    ProperUtil.writeDateToLocalFile("TEST", testContent);

获取保存的信息

 String testContent = ProperUtil.getConfigProperties("TEST");



用起来特别方便。记得权限别忘记添加

<!-- 在SDCard中创建与删除文件权限 -->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <!-- 往SDCard写入数据权限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值