六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 51|回复: 0

配置文件的书写

[复制链接]

升级  30%

3

主题

3

主题

3

主题

童生

Rank: 1

积分
15
 楼主| 发表于 2013-1-15 02:36:48 | 显示全部楼层 |阅读模式
 
最近研究了一下配置文件的读取,经过不断的失败后终于成功了。
下在就把三种方式贴出来。方便大家的学习。
 
1.1 读文件的部分(全部读出,setting_file为文件名称,文件存储在其缓存目录下。)
String data = null;
FileInputStream stream = null;
try {
stream = this.openFileInput(setting_file);
StringBuffer sb = new StringBuffer();
int c;
while ((c = stream.read()) != -1) {
sb.append((char) c);
}
data = sb.toString();
} catch (FileNotFoundException e) {
/* 文件未找到,异常 */
} catch (IOException e) {
/* 文件写入错误 */
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
}
}
}
1.2 写文件的部分
 
StringBuffer data = new StringBuffer();
OutputStream os = null;
try {
os = this.openFileOutput(setting_file, MODE_PRIVATE);
os.write(data.toString().getBytes());
} catch (FileNotFoundException e) {
/* 文件未找到,异常 */
} catch (IOException e) {
/* 文件写入错误 */
} finally {
try {
if (null != os) {
os.close();
os = null;
}
} catch (IOException e) {
}
}
 
2.1 读文件的部分(全部读出,setting_file为文件名称,文件存储在其缓存目录下。)
 
Properties properties = new Properties();
FileInputStream stream = null;
try {
stream = this.openFileInput(setting_file);
properties.load(stream);
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
if (stream != null) {
try {
stream.close();
stream = null;
} catch (IOException e) {
}
}
}
String url=String.valueOf(properties.getProperty("server_url",
"http://"));
 
2.2 写文件的部分
 
Properties properties = new Properties();
properties.setProperty("server_url", "http://www.baidu.com");
FileOutputStream stream = null;
try {
stream = this.openFileOutput(setting_file,
Context.MODE_WORLD_WRITEABLE);
properties.store(stream, "");
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
if (stream != null) {
try {
stream.close();
stream = null;
} catch (IOException e) {
}
}
}
 
 
3.1 读文件的部分(部分读出,文件名称就是类名,文件存储在其缓存目录下。)
SharedPreferences settings = null;
settings = getPreferences(Activity.MODE_PRIVATE);
String url=settings.getString("server_url", "http://");
3.2 写文件的部分
SharedPreferences settings = null;
settings = getPreferences(Activity.MODE_PRIVATE);
 
SharedPreferences.Editor editor = settings.edit();
editor.putString("server_url", "http://www.baidu.com");
editor.commit();
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表