读取写入配置文件
/** 读取配置文件 **/ Properties properties=new Properties(); try { properties.load(getAssets().open("youmay.ini")); //设置常量类的渠道id为配置文件里边的channel Const.CHANNEL_ID=(String) properties.get("channel"); System.out.println("Const.CHANNEL_ID = "+(String) properties.get("channel")); System.out.println("Const.CHANNEL_ID = "+Const.CHANNEL_ID); } catch (IOException e) { e.printStackTrace(); }
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(); } }
//写入配置
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下,并交由系统统一管理
用此方法读写文件时,不能为文件指定具体路径。