如何将特定日志写入txt文件

时间:2013-06-15 21:51:11

标签: java android logging

我有一个应用程序可以写一些日志,比如

Log.d("Device Name", android.os.Build.MODEL);

如何将它们写入SD卡上的.txt文件?

如果我试图运行简单的应用程序,它不保存任何文件

    package com.mycompany.txt;
import android.app.*;
import android.os.*;
import java.io.*;


public class MainActivity extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void appendLog(String text)
{       
   File logFile = new File("/mnt/sdcard/log.file");
   if (!logFile.exists())
   {
      try
      {
         logFile.createNewFile();
      } 
      catch (IOException e)
      {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }
   try
   {
      //BufferedWriter for performance, true to set append to file flag
      BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
      buf.append(text);
      buf.newLine();
      buf.close();
   }
   catch (IOException e)
   {
      // TODO Auto-generated catch block
      e.printStackTrace();
   }
}

}

我是否应该在txt文件中获得完整的日志?

1 个答案:

答案 0 :(得分:0)

here(possible duplicate)复制:

  public void appendLog(String text)
{       
   File logFile = new File(Environment.getExternalStorageDirectory(),"my_app_dir/my_log_file.log");
   if (!logFile.exists())
   {
      try
      {
         logFile.createNewFile();
      } 
      catch (IOException e)
      {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }
   try
   {
      //BufferedWriter for performance, true to set append to file flag
      BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
      buf.append(text);
      buf.newLine();
      buf.close();
   }
   catch (IOException e)
   {
      // TODO Auto-generated catch block
      e.printStackTrace();
   }
}