【问题标题】:How to write specific log to txt file如何将特定日志写入txt文件
【发布时间】:2013-06-15 21:51:10
【问题描述】:

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

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 文件中获取完整的日志吗?

【问题讨论】:

  • 请注意,您通常希望使您的日志标签更加一致以识别您的应用程序或组件,并将您正在登录的内容的描述放在第二个参数中,即Log.d("MyApp", "Device Name " + android.os.Build.Model);
  • "我应该在 txt 文件中获取完整的日志吗?" -- 不,因为你从来没有打电话给appendLog()
  • 这里怎么称呼?

标签: java android logging


【解决方案1】:

复制自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();
   }
}

【讨论】:

  • 对,其他帖子也是这样。我会解决的
  • 这也不一定是有效路径。永远不要硬编码路径。请使用getExternalFilesDir()Environment 上的方法来构建到外部存储的有效路径。
  • 好一点。使用new File(Environment.getExternalStorageDirectory(),"my_log_file.log") 这样您就不必担心getExternalStorageDirectory() 是否有斜杠。此外,您正在做的是将日志转储到外部存储的根目录中。 getExternalFilesDir(),或者Environment.getExternalStoragePublicDirectory(),不要把用户的外部存储根目录弄得那么乱。
  • 感谢您的反馈 :)
猜你喜欢
  • 2020-06-27
  • 1970-01-01
  • 2019-01-08
  • 2013-11-26
  • 2015-10-25
  • 1970-01-01
  • 2012-04-06
  • 2023-03-31
相关资源
最近更新 更多