写入字符串文本文件 [英] Writing String to Text File
本文介绍了写入字符串文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我保存日志.txt文件的SD卡,但一旦有救两条线,它会覆盖它,并重新开始?
I am saving a log to a .txt file on the sdcard but once there is two lines saved, it overwrites it and starts over?
下面是我的code:
public static String getTimestamp() {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("MMMdd HH:mm:ss", Locale.getDefault());
String currentTimeStamp = dateFormat.format(new Date()); // Find todays date
return currentTimeStamp;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void writeToLog(Context context, String string) {
String text = getTimestamp() + " " + string;
// ONLY SAVES TWO LINES
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(logFile, true)));
out.println(text);
out.close();
} catch (IOException e) {
Log.d(Constants.APP_NAME, e.toString());
}
}
只要你安装在恢复/数据,在/ SD卡和放大器的日志文件; /数据/媒体/ 0显示完整的日志历史,但不能当设备上电
As soon as you mount /data in recovery, the log files in /sdcard & /data/media/0 show the full log history but not when the device is powered on
推荐答案
这是它做的方式。下面的示例code后点击提交按钮保存信息到一个文件:
This is the way it is done. The following sample code saves the details to a file upon clicking of the submit button:
Submit = (Button) findViewById(R.id.btnSubmit); //Instantiates the button in the onCreate method
Submit.setOnClickListener(new OnClickListener(){ //Called when the user clicks on the Submit button
@Override
public void onClick(View v) {
// In this case the text to be written is the selected text in a radio button from radioGroup
int Selection = AttendanceGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
RadioButton radiobutton = (RadioButton) findViewById(Selection);
// write on SD card file data in the text box
try {
//gets the current date since this is an attendance app.
Calendar c = Calendar.getInstance();
//Formats the date a desired
SimpleDateFormat date = new SimpleDateFormat("dd-MM-yy");
String getDate = date.format(c.getTime());
//writes the text to the file named attendance.txt which is created in the phone.
File myFile = new File("/sdcard/Albanapp/Attendance.txt");
FileWriter fOut = new FileWriter(myFile, true);
fOut.append(getDate + "\t" + getSelectedName.getSelectedItem().toString() + "\t" + radiobutton.getText().toString() + "\n");
fOut.flush();
fOut.close();
//Returns a statment to the user showing if the editing of the attendance.txt file was successful or not.
Toast.makeText(getBaseContext(),"Status Saved", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), "Attendance cannot be saved",
Toast.LENGTH_SHORT).show();
}
}
});
希望这有助于:)
Hope this helps :)
这篇关于写入字符串文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文