当前位置: 代码迷 >> Android >> Android - Properties使用
  详细解决方案

Android - Properties使用

热度:34   发布时间:2016-04-27 22:49:46.0
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();  	}  }

在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下,并交由系统统一管理

用此方法读写文件时,不能为文件指定具体路径。

我是天王盖地虎的分割线

  相关解决方案