我想在启动我的Android应用程序时在SD卡中创建一个日志文件,并希望将日志写入该文件。如何才能完成?如果有人知道请帮助我..
答案 0 :(得分:1)
我为此创建了类:
public class Logger {
public void appendLog(String text,String filename)
{
File dir = new File("sdcard/YourFolderName");
if(!dir.exists())
{
dir.mkdirs();
}
File logFile = new File("sdcard/YourFolderName/"+filename+".txt");
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)
private File cacheDir;
if(android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"MyLog");
if(!cacheDir.exists())
cacheDir.mkdirs();
它将在SD卡中为您创建一个目录,您可以创建一个文件并在其中写入您的日志。
File f = new File(cacheDir, filename); //(File dirPath,String filename)
使用此行,您可以在目录中创建一个文件,并在该文件中写入日志......
如果这有助于将其标记为正确:)
答案 2 :(得分:0)
在SD卡中创建日志文件
使用此方法。只需将消息作为参数传递给此方法。
public static void addRecordToLog(String message){
//Not in release: Log.d("SmartCalendar", message);
LogRecord logRecord = new LogRecord(Level.INFO, message);
FileHandler logger = null;
if (logger == null) {
try {
logger = new FileHandler(Environment.getExternalStorageDirectory() + "/Android" + Environment.getDataDirectory() + "/dwivedi/files/log_" + new Date().getTime() + ".xml");
} catch (IOException e) {
Log.e("SmartCalendar", e.toString());
// it seems that no dirs on sd card
File dir = new File(Environment.getExternalStorageDirectory() + "/Android" + Environment.getDataDirectory() + "/dwivedi/files/");
dir.mkdirs();
try {
logger = new FileHandler(Environment.getExternalStorageDirectory() + "/Android" + Environment.getDataDirectory() + "/dwivedi/files/log_" + new Date().getTime() + ".xml");
} catch (IOException e1) {
Log.e("SmartCalendar", e1.toString());
return;
}
} catch (Exception e) {
Log.e("SmartCalendar", e.toString());
return;
}
}
logger.publish(logRecord);
}
注意: 不要忘记提供READ和WRITE外部存储的权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>