android数据存储:数据持久化的文件存储
2017-09-26 14:09
309 查看
//将数据存储到文件中 (文件默认存储到:/data/data/<packagename>/files/ 目录下)
openFileOutput(),第一个参数是文件名,第二个参数是文件的操作模式, 主要有两种模式可选,MODE_PRIVATE 和MODE_APPEND。其中MODE_PRIVATE 是默认的操作模式,所写入的内容将会覆盖原文件中的内容,而MODE_APPEND 则表示如果该文件已存在就往文件里面追加内容。
public void save(String inputText) {
FileOutputStream out = null;
BufferedWriter writer = null;
try {
out = openFileOutput("data", Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(inputText);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//从文件中读取数据
public String load() {
FileInputStream in = null;
BufferedReader reader = null;
StringBuilder content = new StringBuilder();
try {
in = openFileInput("data");
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
content.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content.toString();
}
openFileOutput(),第一个参数是文件名,第二个参数是文件的操作模式, 主要有两种模式可选,MODE_PRIVATE 和MODE_APPEND。其中MODE_PRIVATE 是默认的操作模式,所写入的内容将会覆盖原文件中的内容,而MODE_APPEND 则表示如果该文件已存在就往文件里面追加内容。
public void save(String inputText) {
FileOutputStream out = null;
BufferedWriter writer = null;
try {
out = openFileOutput("data", Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(inputText);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//从文件中读取数据
public String load() {
FileInputStream in = null;
BufferedReader reader = null;
StringBuilder content = new StringBuilder();
try {
in = openFileInput("data");
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
content.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content.toString();
}
相关文章推荐
- Android之数据持久化技术一(文件存储)
- 了解 Android 应用的文件存储目录,掌握持久化数据的正确姿势
- android数据持久化技术--文件存储
- android-数据持久化之文件存储
- 详解Android开发数据持久化之文件存储(附源码)
- Android数据持久化功能之一:文件存储
- Android实现数据持久化的文件存储
- Android 数据存储和文件使用案例分析
- android基础---使用文件进行数据存储
- Android数据存储--文件存储
- Android数据存储之文件I/O
- android数据存储之文件存储
- 【Android游戏开发十三】(保存游戏数据 [下文])详解SQLite存储方式,并把SQLite的数据库文件存储在SD卡中!!!
- Android数据存储之文件存储
- android 数据存储和访问方式一:文件详解
- Android数据存储之文件存储
- Android 数据存储和文件使用案例分析
- Android数据存储之文件存储
- Android中的文件存储数据方式
- Android数据存储之文件存储