Android下使用Properties文件保存程序设置
16lz
2021-01-23
读取.properties文件中的配置:
- StringstrValue="";
- Propertiesprops=newProperties();
- try{
- props.load(context.openFileInput("config.properties"));
- strValue=props.getProperty(keyName);
- System.out.println(keyName+""+strValue);
- }
- catch(FileNotFoundExceptione){
- Log.e(LOG_TAG,"config.propertiesNotFoundException",e);
- }
- catch(IOExceptione){
- Log.e(LOG_TAG,"config.propertiesIOException",e);
- }
相信上面这段代码大部分朋友都能看懂,所以就不做过多的解释了。
向.properties文件中写入配置:
- Propertiesprops=newProperties();
- try{
- props.load(context.openFileInput("config.properties"));
- OutputStreamout=context.openFileOutput("config.properties",Context.MODE_PRIVATE);
- Enumeration<?>e=props.propertyNames();
- if(e.hasMoreElements()){
- while(e.hasMoreElements()){
- Strings=(String)e.nextElement();
- if(!s.equals(keyName)){
- props.setProperty(s,props.getProperty(s));
- }
- }
- }
- props.setProperty(keyName,keyValue);
- props.store(out,null);
- Stringvalue=props.getProperty(keyName);
- System.out.println(keyName+""+value);
- }
- catch(FileNotFoundExceptione){
- Log.e(LOG_TAG,"config.propertiesNotFoundException",e);
- }
- catch(IOExceptione){
- Log.e(LOG_TAG,"config.propertiesIOException",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
更多相关文章
- android解析xml文件 Android DOM解析XML之全球实时地震信息列表
- Android通过WebView调用 JS 代码
- android 删除文件,打开指定的文件类型
- Android Studio2.0引入so文件(亲测)
- Android下为自己定义WifiManager类wifi模块代码
- eclipse创建android项目,无法正常预览布局文件
- 如何提高android代码质量
- Android lint 删除无用图片文件和配置文件
- android 开发-数据存储之文件存储