對於我的應用程序,我想創建一個類,我可以將數據記錄到文件中。在我的應用程序中,如果遇到問題,可以通過電子郵件向我發送電子郵件,此文件中的數據可能會幫助我解決問題。首先,我是否以錯誤的方式去做這件事?有沒有更好的方法來記錄發生的異常?FileOutputStream日誌
的問題是,如果我嘗試使用日誌方法使用另一個類:
Logger.log(0,"","","");
它無法找到該文件或事實上,如果尚未創建它創建該文件。代碼附在下面。
package com.example.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
public class Logger extends Activity {
final static String FileName = "Log";
static FileOutputStream fos;
static FileInputStream fis;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("logger", "oncreate");
try {
File f = getFileStreamPath(FileName);
if (!f.exists()) {
Log.d("logger", "file doesn't exist");
fos = openFileOutput(FileName, Context.MODE_APPEND);
fos.write(("Created on " + Build.TIME + "\nDevice name: "
+ Build.MODEL + " \nAndroid Version" + Build.VERSION.SDK_INT)
.getBytes());
fos.close();
}
fos = openFileOutput(FileName, Context.MODE_APPEND);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void log(int type, String TAG, String msg) {
Log.d("logger", "file being written");
Log.println(type, TAG, msg);
Time now = new Time();
now.setToNow();
try {
fos = new FileOutputStream(FileName);
fos.write(("\n" + now.toString() + " " + type + " " + TAG + " " + msg).getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}