Android持久化存储,主要的方法有文件存储、sharedpreference及数据库,这里主要实现文件存储,包括将字符串保存到文件中以及从文件中获取字符串。
注意:
1.所有文件默认存储到/data/data/packagename/files/目录下
2.文件的操作模式主要有两种,MODE_PRIVATE(默认的操作模式,写入的内容会覆盖原文件中的内容)、MODE_APPEND(如果该文件已存在就追加内容,不存在就创建新文件)。

package com.czhappy.animationdemo.utils;

import android.content.Context;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/**
* Description:
* User: chenzheng
* Date: 2016/12/16 0016
* Time: 17:50
*/
public class FileUtils {

/**
* 将字符串保存到文件中
* @param context
* @param data 需要保存的字符串
* @param fileName 保存的文件名
*/
public static void saveStringToFile(Context context, String fileName, String data){
FileOutputStream out = null;
BufferedWriter writer = null;
try{
out = context.openFileOutput(fileName, Context.MODE_PRIVATE);//文件名为data
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(data);
}catch (IOException e){
e.printStackTrace();
}finally {
try {
if (writer != null) {
writer.close();
}
}catch (IOException e){
e.printStackTrace();
}
}

}

/**
* 从文件中读取字符串
* @param context
* @param fileName 文件名
* @return
*/
public static String getStringFromFile(Context context, String fileName){
FileInputStream in = null;
BufferedReader reader = null;
StringBuffer content = new StringBuffer();
try{
in = context.openFileInput(fileName);
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while((line = reader.readLine()) != null){
content.append(line);

}
}catch (IOException e){
e.printStackTrace();
}finally {
try {
if (reader != null) {
reader.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
return content.toString();
}
}