android logcat日誌保存到文件中

package com.android.write;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class SaveLog extends Thread {

    private String shell = "logcat";
    private String logpath = "/mnt/sdcard2/logcat.txt";
    private BufferedReader mReader;
    private Process process = null;
    private FileOutputStream fos = null;
    private InputStream inputStream= null;
    private boolean mRunning = true;
    private BufferedWriter bw = null;
    private File file = null;
    
    public SaveLog() {
        file = new File(logpath);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file, true);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void run() {
        try {
            
            process = Runtime.getRuntime().exec(shell);
            inputStream = process.getInputStream();
            mReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = null;
            while ((line = mReader.readLine()) != null){
                file = new File(logpath);
                if (!file.exists()) {
                    file.createNewFile();
                    fos = new FileOutputStream(file, true);
                }
                if (file.length() > 1 * 1024 * 1024) {
                    FileOutputStream fos = new FileOutputStream(file);
                    fos.write("".getBytes());
                    fos.close();
                    clearLogCache();
                }
                if (line.length() == 0) {
                    continue;
                }
                if (fos != null) {
                    fos.write((line + "\n").getBytes());
                }
                
            }
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
            
    }

    
      private void clearLogCache() {
          Process proc = null;
          List<String> commandList = new ArrayList<String>();
          commandList.add("logcat");
          commandList.add("-c");
          //commandList.add("*:E");// 過濾所有的錯誤信息
          try {
            proc = Runtime.getRuntime().exec(
                      commandList.toArray(new String[commandList.size()]));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
          
      }

}


<uses-permission android:name="android.permission.READ_LOGS" />


發佈了6 篇原創文章 · 獲贊 2 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章