2013-07-12 99 views
0

我寫了一個方法來打印日誌文件。這是行得通的。我唯一擔心的是日誌已被新日誌取代。有什麼辦法保持日誌附加?如何在SDCard中寫入文件時繼續追加日誌?

public static void printLog(Context context){ 
String filename = context.getExternalFilesDir(null).getPath() + File.separator + "my_app.log"; 
String command = "logcat -d *:V"; 

Log.d(TAG, "command: " + command); 

try{ 
    Process process = Runtime.getRuntime().exec(command); 

    BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); 
    String line = null; 
    try{ 
     File file = new File(filename); 
     file.createNewFile(); 
     FileWriter writer = new FileWriter(file); 
     while((line = in.readLine()) != null){ 
      writer.write(line + "\n"); 
     } 
     writer.flush(); 
     writer.close(); 
    } 
    catch(IOException e){ 
     e.printStackTrace(); 
    } 
} 
catch(IOException e){ 
    e.printStackTrace(); 
} 
} 
+0

您每次寫入時都要重新創建一個'File'。相反,你應該在你的try塊中checkIfFileExist,如果yes =>追加你的日誌消息。看看這個圖書館:http://acra.ch/ – longilong

回答

2

嘗試這個:

public static void printLog(String logData) { 

    try { 
     File logFile = new File(Environment.getExternalStorageDirectory(), 
       "yourLog.txt"); 
     if (!logFile.exists()) { 
      try { 
       logFile.createNewFile(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
     try { 
      BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, 
        true)); 
      buf.append(logData); 
      buf.newLine(); 
      buf.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } catch (Exception e) { 
       e.printStackTrace(); 
    } 
} 

您不是以追加模式寫入文件。 使用new FileWriter(file,true)而不是new FileWriter(file)

+0

謝謝Rihan ...這也是工作 – user2568219