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("讀取日誌錯誤");
            }
        }
    }
相關文章
相關標籤/搜索