2

我正在尝试将日志语句写入 sdcard。我决定这样做的方式是通过应用程序对象在 sdcard 上创建一个文件。这样我就可以从应用程序的任何地方调用静态方法 logToSdcard()。

包含文件夹“/RR3log/”已创建,但我记录的每条语句都在其自己的名为“rr3LogFile.txt”的文件中。所以我有多个 rr3LogFile 文件,每个文件都包含一个语句。

如何将所有语句写入一个 rr3LogFile 文件?在此先感谢马特。

public class NfcScannerApplication extends Application{

    @Override
    public void onCreate() {
        super.onCreate();




        File storageDir = new File(Environment
                .getExternalStorageDirectory(), "/RR3log/");


        storageDir.mkdir();
        try {

            if(outfile == null){
            outfile=File.createTempFile("rr3LogFile", ".txt",storageDir);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }





public static void logToSdcard(String tag, String statement){


        Log.e(TAG, "inside logtosdcard$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");


                String state = android.os.Environment.getExternalStorageState();
                if(!state.equals(android.os.Environment.MEDIA_MOUNTED))  {
                    try {
                        throw new IOException("SD Card is not mounted.  It is " + state + ".");
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                DateTime now = new DateTime();
                DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y H:mm");
                String dateStr = fmt.print(now);


                try{


                    FileOutputStream fOut = new FileOutputStream(outfile);
                    OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
                    myOutWriter.append(dateStr + " " + tag + "     ");
                    myOutWriter.append(statement);
                    myOutWriter.append("\n");
                    myOutWriter.flush();
                    myOutWriter.close();
                    fOut.close();

                }catch(IOException e){
                    e.printStackTrace();
                }




    }


}

.

然后在应用程序中的任何位置的 Activity 中。

@Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "inside entryactivity onResume");
        NfcScannerApplication.logToSdcard(TAG, "inside entryactivity onResume" );
4

2 回答 2

5

在您的logToSdcard方法中,使用附加参数创建 FileOutputStream:

FileOutputStream fOut = new FileOutputStream(outfile, true);

true参数表示内容将附加到文件中。另请参阅FileOutputStream

于 2013-07-16T14:20:09.290 回答
4

试试看:

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

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

    try{
        Runtime.getRuntime().exec(command);
    }
    catch(IOException e){
        e.printStackTrace();
    }
}

日志将持续保存,直到应用程序退出。

于 2013-07-17T09:25:16.153 回答