读写本地文件

读写本地文件呢刚开始学的时候也没当回事,发现到用的时候发现以前学的多多少少有点问题,上网查询发现读写文件的方法有好多种,虽说大同小异,但本人喜欢找一个好的方法,记住它,就一直用它

我用到读写文件呢是在做本地缓存,在有网的情况下向本地文件写入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;
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值