android 日志文件输出

android 日志文件输出

用法:

try {
            
        } catch (Exception e) {
            LogUtil.LogException(e);
        }

package com.hexun.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.StringWriter;

import android.os.Environment;
import android.util.Log;

/**
 * 日志打印
 */
public class LogUtil {

    private static final String FILE_NAME = "/logs.txt";
    private static Boolean MYLOG_SWITCH = true; // 日志文件总开关

    public static void i(String tag, String str) {
        Log.i(tag, str.toString());
    }

    public static void LogException(Exception e) {
        if (MYLOG_SWITCH) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            String str = sw.toString();
            writeException(str);
        } else {
            e.printStackTrace();
        }
    }

    private static void writeException(String content) {
        try {
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                // 获取SD卡的目录
                File sdCardDir = Environment.getExternalStorageDirectory();
                File targetFile = new File(sdCardDir.getCanonicalPath()
                        + FILE_NAME);
                // 以指定文件创建RandomAccessFile对象
                RandomAccessFile raf = new RandomAccessFile(targetFile, "rw");
                // 将文件记录指针移动到最后
                raf.seek(targetFile.length());
                // 输出文件内容
                raf.write(content.getBytes());
                raf.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String readException() {
        try {
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                // 获得SD卡对应的存储目录
                File sdCardDir = Environment.getExternalStorageDirectory();
                // 获取指定文件对应的输入流
                FileInputStream fis = new FileInputStream(
                        sdCardDir.getCanonicalPath() + FILE_NAME);
                // 将指定输入流包装成BufferReader
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        fis));
                StringBuilder sb = new StringBuilder("");
                String line = null;
                // 循环读取文件内容
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                return sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}


你可能感兴趣的:(android,日志,log)