-、 放在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; } }
浙公网安备 33010602011771号