配置文件的书写

 

最近研究了一下配置文件的读取,经过不断的失败后终于成功了。

下在就把三种方式贴出来。方便大家的学习。

 

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();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值