Android 读写日志文件

重要的点

  1. 把错误信息保存到一个String变量中
public static void print(String str){
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            fw =  new FileWriter(logFilePath);
            bw =  new BufferedWriter(fw);
            bw.write(str);
            bw.write("\n");
            bw.newLine();
            bw.flush();
            bw.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  1. 获取文件的大小
FileInputStream is = new FileInputStream(logFile);
                int length = is.available();
  1. 获取Android Cache 目录
public static final String logFilePath = MyApplication.getMyApplicationContext().getCacheDir()+"/myLog.txt";
  1. 读取文件的方法 并转换成String
private void readFile() {
        File file = new File(LogFileUtil.logFilePath);
        if (file.exists()) {
            try {
                FileInputStream fis = new FileInputStream(file);
                int length = fis.available();
                logFileInfo = "文件路径: \n" + LogFileUtil.logFilePath + "\n";
                logFileInfo = logFileInfo + "length: " + length + " byte\n";
                byte[] buffer = new byte[length];
                fis.read(buffer);
                String ss = new String(buffer, "UTF-8");
                mTvLogContent.setText(ss);
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
                mTvLogContent.setText("读取日志错误");
            }
        }
    }

转载于:https://my.oschina.net/u/3136970/blog/917625

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值