Android下用Properties保存程序配置

http://blog.163.com/willhuang_78/blog/static/12712835201292393832481/

android读取properties文件方法 

java中经常用到properties文件,然后通过使用Properties类来解析。
方法一:
因为最终是通过流文件来进行读取properties文件的,所以很自然,我们想到要将文件放入到assets文件夹或者raw文件夹中。
例如,我们这里有一个文件:test.properties,如果放入了assets文件夹中,可以如下打开
Properties pro = new Properties();
InputStream is = context.getAssets().open("test.properties");
pro.load(is);
如果放入到raw文件夹中,可以通过如下方式打开
InputStream is = context.getResources().openRawResource(R.raw.test);
但是,有的时候我们不想获取android的上下文环境(context),而是像java中标准的方法加载properties文件,那么我们如何使用呢?
方法二:没有上下文的加载![推荐方式]
Properties pro = new Properties();
pro.load(FileLoad.class.getResourceAsStream("test.properties"));
其中,FileLoad是该加载方法所在类的类名。test.properties所存放的路径与FileLoad.java为同一包中。
但是,在android中,当我们打包生成apk后,将apk放入到真正的手机上时,会找不到test.properties文件,不要惊讶,
android中的资源文件是只能存放在assets或者res的子目录里面的,程序包中的资源文件编译后,是会丢失的!那么是不是我们的第二种方 法就没法使用了? 当然不是,将文件放入到assets文件夹里,而在传入路径里面填入文件绝对路径,还是可以引用该文件的。
代码:
pro.load(FileLoad.class.getResourceAsStream("/assets/test.properties"));
注意:其中工程路径的根路径为"/"

-------------------------------------------------------------------------------------------------------------------------------------------------------

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.Enumeration;

import java.util.Properties;

import android.content.Context;

public class RecConfigFile {

    private Properties urlProps; //属性对象   

    private static final String path = "/data/data/com.android.bbksoundrecorder/setting.properties";

    public Properties loadConfig(Context context, String file) {

        Properties properties = new Properties();

        try {

            FileInputStream s = new FileInputStream(file);

            properties.load(s);

        } catch (Exception e) {

            e.printStackTrace();

        }

        return properties;

    }

    public void saveConfig(Context context, String file, Properties properties) {

        try {

            FileOutputStream s = new FileOutputStream(file, false);

            properties.store(s, "");

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    

    //private FileUtils fu = new FileUtils();

    public static Properties getProperties() {

        Properties props = new Properties();

        try {

            InputStream in = new FileInputStream(getSettingFile());

            props.load(in);

        } catch (Exception e1) {

            // TODO Auto-generated catch block

            e1.printStackTrace();

        }

        urlProps = props;

        return urlProps;

    }

    public static void setProperties(String param, String value) {

        Properties props = new Properties();

        try {

            props.load(new FileInputStream(getSettingFile()));

            OutputStream out = new FileOutputStream(getSettingFile());

            Enumeration<?> e = props.propertyNames();

            if (e.hasMoreElements()) {

                while (e.hasMoreElements()) {

                    String s = (String) e.nextElement();

                    if (!s.equals(param))

                        props.setProperty(s, props.getProperty(s));

                }

            }

            props.setProperty(param, value);

            props.store(out, null);

            // 测试是否能够打印出最新的,刚刚修改的url的值

            // System.out.println("setProperty success: " +

            // props.getProperty(param));

        } catch (IOException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

    private static File getSettingFile() {

        File setting = new File(path);

        if (!setting.exists()){

            try{

                setting.createNewFile();

            }catch (IOException ex) {

                ex.printStackTrace();

            }

        }

        return setting;

    }

}

-----------------------------------------------------------------------------------------------------------------------------------------

Android 对 properties文件的读写操作 

-、 放在res中的properties文件的读取,例如对放在assets目录中的setting.properties的读取:
PS:之所以这里只是有读取操作,而没有写的操作,是因为我发现不能对res下的资源文件进行操作,当然包括assets下的properties文件了。如对res资源目录下的properties进行写的操作,那么在你获得properties的FileOutputStream的实例时会报FileNotFoundException的异常。
代码如下(操作写成一个PropertiesUtil工具类):
setting.properties中的代码:

url=http://localhost:8080


PropertiesUtil 工具类:
  
  
public class PropertiesUtil {
private static Properties urlProps ;
        public static Properties getProperties ( Context c ){
Properties props = new Properties ();
try { //方法一:通过activity中的context攻取 setting.properties的FileInputStream
InputStream in = c. getAssets().open(" setting.properties   "); //方法二:通过class获取setting.properties的FileInputStream //InputStream in = PropertiesUtill.class. getResourceAsStream("/assets/   setting.properties   ")); 
props.load(in);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
urlProps = props; //测试是否能获得setting.properties中url的值 System . out . println ( urlProps . getProperty ( "url" ));          return urlProps ;
}
}

二、对不是放在res资源目录下的properties文件的操作,如放在activity 的 包(package)目录下的setting.properties文件的读写操作。
setting.properties的代码还是一样的,只是路径不同,而是在activity的包(如:com.jansun.activity)目录下:

url=http://localhost:8080

PropertiesUtil工具类:
 
 
public class PropertiesUtil {
private static Properties urlProps ;
private static final path = "/data/data/com.jansun.activity/setting.properties" ;
//private FileUtils fu = new FileUtils();
public static Properties getProperties(){
Properties props = new Properties();
try {
InputStream in = new FileInputStream(getSettingFile());
props.load(in);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
urlProps = props;
return urlProps;
}
public static void setProperties( String param, String value ){
Properties props = new Properties();
try {
props.load(new FileInputStream( getSettingFile()  ));
OutputStream out = new FileOutputStream(FileUtils.setting);
Enumeration<?> e = props.propertyNames();
if(e.hasMoreElements()){
while(e.hasMoreElements()){
String s = (String)e.nextElement();
if(!s.equals(param))
props.setProperty(s, props.getProperty(s));
}
}
props.setProperty(param, value);
props.store(out, null); //测试是否能够打印出最新的,刚刚修改的url的值
//System.out.println("setProperty success: " + props.getProperty(param));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static File getSettingFile(){ File setting = new File ( path ); if (! setting . exists ()) setting . createNewFile (); return setting ; }
}
-----------------------------------------------------------------------------------------------------------

Android下用Properties保存程序配置

读写函数分别如下:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;

public Properties loadConfig(Context context, String file) {
Properties properties = new Properties();
try {
FileInputStream s = new FileInputStream(file);
properties.load(s);
} catch (Exception e) {
e.printStackTrace();
}
return properties;
}

public void saveConfig(Context context, String file, Properties properties) {
try {
FileOutputStream s = new FileOutputStream(file, false);
properties.store(s, "");
} catch (Exception e){
e.printStackTrace();
}
}

orz,是不是发现什么了?对了,这两个函数与Android一点关系都没有嘛。。
所以它们一样可以在其他标准的java程序中被使用
在Android中,比起用纯字符串读写并自行解析,或是用xml来保存配置,
Properties显得更简单和直观,因为自行解析需要大量代码,而xml的操作又远不及Properties方便

使用方法如下:
写入配置:
Properties prop = new Properties();
prop.put("prop1", "abc");
prop.put("prop2", 1);
prop.put("prop3", 3.14);
saveConfig(this, "/sdcard/config.dat", prop);

读取配置:
Properties prop = loadConfig(this, "/sdcard/config.dat");
String prop1 = prop.get("prop1");

注:也可以用Context的openFileInput和openFileOutput方法来读写文件
此时文件将被保存在 /data/data/package_name/files下,并交由系统统一管理
用此方法读写文件时,不能为文件指定具体路径。
http://www.samool.com/archives/41507/
---------------------------------------------------------------------------------------------------------------------------------------------------------------

Android使用Properties文件保存信息的永久链接

应用程序有时可能需要保存一些简单的信息,以供下次使用时恢复上一次使用的状态。因为信息比较简单,所以没必要使用数据库进行保存,这时可以使用properties文件来保存,使用起来也比较简单。以一个例子来说明,下面的例子仅仅简单的显示上一次使用时界面显示的语言内容,主要涉及到java.util.Properties这个类,读写文件会用到Activity从曾祖父类(呵呵,咱这么称呼的)Context继承的方法openFileInput(String name)获得输入流,openFileOutput(String name, int mode)方法获得输出流。按下导航的↑方向键,切换到中文界面,按下导航的↓方向键,切换到英文界面(仅内容区域,不涉及到标题),第一次进入时因为没有配置文件,故设置为默认的英文界面。具体代码如下:

package com.jade.file;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.TextView;

public class FileProperties extends Activity {
    private TextView tv = null;
    private String lan = null;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) findViewById(R.id.txtview1);
        Properties properties = new Properties();
        try {
		properties.load(openFileInput("language.properties"));
		lan = properties.getProperty("language");
		tv.setText(lan);
	} catch (Exception e) {
		e.printStackTrace();
		tv.setText("This is the default language English.");
	}
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
	switch(keyCode) {
	case KeyEvent.KEYCODE_DPAD_UP:
		tv.setText("您正在使用中文。");
		lan = "您正在使用中文。";
		break;
	case KeyEvent.KEYCODE_DPAD_DOWN:
		tv.setText("You are using English now.");
		lan = "You are using English now.";
		break;
	case KeyEvent.KEYCODE_BACK:
		saveLan();
		this.finish();
		break;
	}
	return super.onKeyUp(keyCode, event);
    }

    private void saveLan() {
	Properties p = new Properties();
	p.setProperty("language", lan);
	try {
	    p.store(openFileOutput("language.properties", MODE_WORLD_WRITEABLE), null);
	} catch (FileNotFoundException e) {
	    e.printStackTrace();
	} catch (IOException e) {
	    e.printStackTrace();
	}
    }
}

运行程序后,默认界面如下图所示:

这时按下方向键↑,就会转换成如下图所示的中文界面:

进入中文界面后,按下“返回”键,程序退出,然后进入菜单找到程序重新启动,可以看到程序仍然是中文界面,因为这次配置文件已经存在,所以可以读到已经保存的信息。配置文件保存的位置在data/data/com.jade.file/files/language.properties,可以在FileExplorer里找到,下载的电脑上打开可以看到如下内容:

#Tue May 17 06:52:50 GMT 2011
language=\u60a8\u6b63\u5728\u4f7f\u7528\u4e2d\u6587\u3002

字符是以UTF-8格式保存的。在中文界面下,按下下方向键↓,可以看到进入下图所示的英文界面:

这时按下返回键退出程序,仍然去找到language.properties文件,打开之后可以看到内容如下:

#Tue May 17 06:56:18 GMT 2011
language=You are using English now.

可以看到程序保存的语言设置已经变成英文的了。下次启动程序的时候,界面默认就是英文界面了。

小小知识点:Properties类是继承自Hashtable,因此可以使用类Hashtable、Dictionary以及接口Map的相关方法,具体参考API文档。

本文固定链接: http://www.tidroid.com/article_16.html | 泰卓网

---------------------------------------------------------------------------------------------------------------------------------------------------------------

Android下使用Properties文件保存程序设置

读取.properties文件中的配置: 
   
   
  1. String strValue = ""
  2. Properties props = new Properties(); 
  3. try { 
  4.     props.load(context.openFileInput("config.properties")); 
  5.     strValue = props.getProperty (keyName); 
  6.     System.out.println(keyName + " "+strValue); 
  7. catch (FileNotFoundException e) { 
  8.     Log.e(LOG_TAG, "config.properties Not Found Exception",e); 
  9. catch (IOException e) { 
  10.     Log.e(LOG_TAG, "config.properties IO Exception",e); 

    相信上面这段代码大部分朋友都能看懂,所以就不做过多的解释了。

    向.properties文件中写入配置:

   
   
  1. Properties props = new Properties(); 
  2. try { 
  3.     props.load(context.openFileInput("config.properties")); 
  4.     OutputStream out = context.openFileOutput("config.properties",Context.MODE_PRIVATE); 
  5.     Enumeration<?> e = props.propertyNames(); 
  6.     if(e.hasMoreElements()){ 
  7.         while (e.hasMoreElements()) { 
  8.             String s = (String) e.nextElement(); 
  9.             if (!s.equals(keyName)) { 
  10.                 props.setProperty(s, props.getProperty(s)); 
  11.             } 
  12.         } 
  13.     } 
  14.     props.setProperty(keyName, keyValue); 
  15.     props.store(out, null); 
  16.     String value = props.getProperty(keyName); 
  17.     System.out.println(keyName + " "+value); 
  18. catch (FileNotFoundException e) { 
  19.     Log.e(LOG_TAG, "config.properties Not Found Exception",e); 
  20. catch (IOException e) { 
  21.     Log.e(LOG_TAG, "config.properties IO Exception",e); 

    上面这段代码,跟读取的代码相比,多了一个if判断以及一个while循环。主要是因为Context.Mode造成的。因为我的工程涉及到多个配置信息。所以只能是先将所有的配置信息读取出来,然后在写入配置文件中。
    Context.Mode的含义如下:
    1.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容。
    2.MODE_APPEND:代表该文件是私有数据,只能被应用本身访问,该模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
    3.MODE_WORLD_READABLE:表示当前文件可以被其他应用读取。
    4.MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。

    注:.properties文件放置的路径为/data/data/packagename/files

同意

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值