|
|
最近研究了一下配置文件的读取,经过不断的失败后终于成功了。
下在就把三种方式贴出来。方便大家的学习。
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(); |
|