读写本地文件呢刚开始学的时候也没当回事,发现到用的时候发现以前学的多多少少有点问题,上网查询发现读写文件的方法有好多种,虽说大同小异,但本人喜欢找一个好的方法,记住它,就一直用它
我用到读写文件呢是在做本地缓存,在有网的情况下向本地文件写入Json等格式字符串,在没网的时候拿出来直接用(解析啊等……)方便快捷,当然存本地数据库也很方便;
所以今天路过,留下读写文件方法
像这种用起来频繁的方法,我都喜欢放到工具类里,所以在此直接就按在工具类里写:
向文件写入内容
public static void saveData(String str,String file,Context context) {//1.要写入的字符串,2、文件名字 3、上下文
try {
FileOutputStream output = context.openFileOutput(file, context.MODE_PRIVATE);//1、文件名 2、文件的写入模式
byte b[] = str.getBytes();//将字符串转化为字节数组
output.write(b);//写入
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
读取文件内容:
public static String getData(String file,Context context) {//文件名 上下文
String content = "";
try {
FileInputStream input = context.openFileInput(file);
if (input != null) {
InputStreamReader inputStreamReader = new InputStreamReader(input);//将字节流转成字符流,提高读取效率;InputStreamReader 是字节流通向字符流的桥梁
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);//BufferedReader 具有读取文本行的功能,传入对象的是一个reader;
String line = "";
while ((line = bufferedReader.readLine()) != null) {//一行一行读取
content += line;
}
input.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return content;
}
附加工具类里判断是否有网络方法
/**
* 检测网络是否连接
*
* @return
*/
public static boolean isNetwork(Context context) {
// 得到网络连接信息
ConnectivityManager manager = (ConnectivityManager)context. getSystemService(Context.CONNECTIVITY_SERVICE);
// 去进行判断网络是否连接
if (manager.getActiveNetworkInfo() != null) {
return manager.getActiveNetworkInfo().isAvailable();
}
return false;
}