Android中读取properties文件

来源:互联网 发布:linux 系统添加wifi 编辑:程序博客网 时间:2024/06/05 01:51
    通过流文件来进行properties文件读取的,要将文件放入到assets文件夹或者raw文件夹中.例如,我们这里有一个文件test.properties,如果放入了assets文件夹中,可以如下打开: 
Java代码  
  1. Properties pro = new Properties();  
  2. InputStream is = context.getAssets().open("test.properties");   
  3. pro.load(is);  

    如果放入到raw文件夹中,可以通过如下方式打开: 

Java代码  收藏代码
  1. InputStream is = context.getResources().openRawResource(R.raw.test);  

    
Java代码  
  1. Properties pro = new Properties();  
  2. pro.load(FileLoad.class.getResourceAsStream("/assets/test.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下,并交由系统统一管理
用此方法读写文件时,不能为文件指定具体路径。
    在android中,当我们打包生成apk后,将apk放入到真正的手机上时,你会找不到test.properties文件,不要惊讶,android中的资源文件是只能存放在assets或者res的子目录里面的,程序包中的资源文件编译后,是会丢失的!那么是不是我们的第二种方法就没法使用了?当然不是,经过实验发现,将文件放入到assets文件夹里,而在传入路径里面填入文件绝对路径,还是可以引用该文件的.
 
 
原创粉丝点击