您好,我正在尝试将logcat的内容保存到手机存储中我的应用程序中的文件中,然后从应用程序中以字符串形式读取它的内容。
最终,我只想保存包含MediaMetadata的行(并使用正则表达式来执行此操作),但是现在我在读取文件内容时遇到了麻烦。
我相信我已成功将logcat保存到文件中,但是一旦我为文件路径调用openFileInput,我的程序就会不断崩溃。
在MainActivity中,每当我按下一个按钮时,我都会调用此函数:
public void onCreate(Context context) throws Exception {
//write file
super.onCreate();
String filename = "temp";
String filepath = "temp";
if ( isExternalStorageWritable() ) {
File appDirectory = new File( Environment.getExternalStorageDirectory() + "/MyPersonalAppFolder" );
//appDirectory = /storage/emulated/0/MyPersonalAppFolder
File logDirectory = new File( appDirectory + "/log" );
//logDirectory = /storage/emulated/0/MyPersonalAppFolder/log
filename = "logcat" + System.currentTimeMillis() + ".txt";
filepath = logDirectory+"/"+filename;
//filepath = /storage/emulated/0/MyPersonalAppFolder/log/logcat1552017420176.txt
Log.i("myTag", "filename = "+filename);
Log.i("myTag", "filepath = "+filepath);
File logFile = new File( filepath );
// create app folder
if ( !appDirectory.exists() ) {
appDirectory.mkdir();
}
// create log folder
if ( !logDirectory.exists() ) {
logDirectory.mkdir();
}
// clear the previous logcat and then write the new one to the file
try {
//Process process = Runtime.getRuntime().exec( "logcat -c");
Process process = Runtime.getRuntime().exec( "logcat -d -f " + logFile );
//Process process = Runtime.getRuntime().exec( "logcat -e \b(updateMediaMetaData) -f " + logFile );
} catch ( IOException e ) {
e.printStackTrace();
}
} else if ( isExternalStorageReadable() ) {
// only readable
} else {
// not accessible
}
//read file
Log.i("myTag", "now going to read file at filepath = "+filepath);
String ret = "tempretoncreate";
FileInputStream fis;
Log.i("myTag", " here0");
fis = openFileInput(filepath);
Log.i("myTag", " here1");
StringBuffer fileContent = new StringBuffer("");
Log.i("myTag", " here2");
//fis.close();
Log.i("myTag", " ret = "+ret);
Log.i("myTag", " end of onCreate() func");
}
**我的logcat调试语句类似于
2019-03-07 20:23:49.848 4634-4634 / com.example.savefile I / myTag:单击了按钮 2019-03-07 20:23:49.859 4634-4634 / com.example.savefile I / myTag:文件名= logcat1552019029859.txt 2019-03-07 20:23:49.860 4634-4634 / com.example.savefile I / myTag:文件路径= /storage/emulated/0/MyPersonalAppFolder/log/logcat1552019029859.txt 2019-03-07 20:23:49.867 4634-4634 / com.example.savefile I / myTag:现在将在文件路径= /storage/emulated/0/MyPersonalAppFolder/log/logcat1552019029859.txt中读取文件 2019-03-07 20:23:49.867 4634-4634 / com.example.savefile I / myTag:here0 2019-03-07 20:23:49.873 4634-4634 / com.example.savefile I / myTag:错误调用onCreate 2019-03-07 20:23:49.873 4634-4634 / com.example.savefile I / myTag:btnClick()函数的结尾
所以最后被调用的是我的'here0'打印语句,这使我认为我没有在文件路径上正确调用openFileInput(“ /storage/emulated/0/MyPersonalAppFolder/loglogcat1552017420176.txt")
在我的android应用中将文件作为字符串读取文件是否正确?