Android存储Log日志到SD卡

本文介绍了一种在Android环境中实现日志文件读写的简单方法,包括创建文件、写入日志及读取日志的具体步骤,并强调了必要的权限设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 *读取文件
 */
private String read() {
    String path = "/data/data/你得包名/logs/";
    String name = "x.txt";
    BufferedReader reader = null;
    try {
        FileInputStream f = new FileInputStream(path + name);
        reader = new BufferedReader(new InputStreamReader(f));
        String line;
        String lines = "";
        while ((line = reader.readLine()) != null) {
            line += "\r\n";
            lines = lines + line;
        }
        return lines;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "...........";
}

//检测路径是否存在
private void isHavePath(String path) {
    File file = new File(path);
    if (!file.exists()) {
        file.mkdirs();
    }
}

//获取 log 日志的线程,保存成 text
@Override
public void run() {

    String path = "/data/data/你程序的包名/logse/";
    String name = "x.txt";
    try {
        //获取logcat日志信息
        isHavePath(path);
        File file = new File(path + name);
        String str = "hello world";
        FileWriter fw = new FileWriter(file + "as.txt");
        fw.flush();
        fw.write(str);
        fw.close();


    } catch (Exception e) {
        e.printStackTrace();
    }
}
不要忘记添加权限
<uses-permission android:name="android.permission.READ_LOGS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
大家加油
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值