我正在将日志保存到SD卡上的.txt文件中,但是一旦保存了两行,它会覆盖它并重新开始?
这是我的代码:
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());
}
}
一旦你在恢复中挂载/数据,/ sdcard&中的日志文件就会出现。 / data / media / 0显示完整的日志历史记录,但不显示设备启动时
答案 0 :(得分:3)
你可以简单地使用FileWriter
而不用所有链接的其他作家。请务必调用flush()
,因为这样可以确保将所有缓冲的内容写入文件
如果仍然无法正常工作,请检查错误输出。
public static void writeToLog(Context context, String string) {
String text = getTimestamp() + " " + string + "\n"; //newline here
Writer out;
try {
out = new FileWriter(logFile, true);
out.append(text);
out.flush(); //ensure that all buffered characters are written to the target
} catch (IOException e) {
Log.d(Constants.APP_NAME, e.toString());
} finally {
if (out != null) {
out.close(); //ensure writer is closed
}
}
}
答案 1 :(得分:2)
使用NIO,您可以更有效地写入文件的末尾
public static void writeToLog(String string) {
String text = getTimestamp() + " " + string;
try {
java.nio.file.Files.write(java.nio.file.Paths.get("/file.txt"), text.getBytes(), java.nio.file.StandardOpenOptions.APPEND);
} catch (IOException ignore) { }
}
答案 2 :(得分:1)
您只需调用一次写入,并且您希望立即写入该文件。您不需要BufferedWriter或PrintWriter。他们的开销很大。此外,应该从 finally {} 块调用close,因为如果您有错误,仍然需要关闭它。
public static void writeToLog(Context context, String string) {
String text = getTimestamp() + " " + string + "\n";
Writer out = null;
try {
out = new FileWriter(logFile, true);
out.write(text, 0, text.length());
} catch (IOException e) {
Log.d(Constants.APP_NAME, e.toString());
} finally {
if (out != null){
out.close();
}
}
}
如果您在文件打开时要进行多次写入,则只声明BufferedWriter。 BufferedWriter的目的是通过跟踪已经输入的内容与已经刷新的内容来提高多次写入的效率。
我看到的另一个问题是,因为这是一个静态方法而且编写器不是静态的,所以多次调用可能会尝试同时调用writeToLog。
如果您使用的是Java 7或更高版本,则可以使用尝试使用资源语句来自动关闭您的编写器,从而简化这一过程:
public static void writeToLog(Context context, String string) {
String text = getTimestamp() + " " + string + "\n";
try (FileWriter out = new FileWriter(logFile, true)) {
out.write(text, 0, text.length());
} catch (IOException e) {
Log.d(Constants.APP_NAME, e.toString());
}
}
如果您每隔一秒可能多次记录一行,您可能需要考虑保持编写器打开,因为打开/关闭会导致很多开销。它还确保您对writeToLog()的所有调用都按顺序发送到同一个编写器。
private static final PrintWriter logWriter =
new PrintWriter(new BufferedWriter(new FileWriter(logFile, true)));
private static int flushCounter = 0;
private static final int flushFrequency = 5; // Flush the buffer every 5 lines
public static void writeToLog(Context context, String string) {
String text = getTimestamp() + " " + string + "\n";
try {
logWriter.write(text, 0, text.length());
} catch (IOException e) {
Log.d(Constants.APP_NAME, e.toString());
} finally {
flushCounter++;
if (flushCounter > flushFrequency){ // flush every 5 lines
logWriter.flush();
flushCounter = 0;
}
}
}
public void close(){
logWriter.close();
}
您可以在调用代码中从 finally {} 块调用close()来清理logWriter。
答案 3 :(得分:1)
我可以使用您的代码附加文件,请查看此代码
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class Test {
public static String getTimestamp() {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"MMMdd HH:mm:ss", Locale.getDefault());
String currentTimeStamp = dateFormat.format(new Date());
return currentTimeStamp;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void writeToLog(String string) {
String text = getTimestamp() + " " + string;
// ONLY SAVES TWO LINES
try {
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("c:/log.txt", true)));
out.println(text);
out.close();
} catch (IOException e) {
}
}
public static void main(String[] args) throws Exception {
writeToLog("Connected to WIFI");
}
}
OUPUT:
Sep05 16:13:28连接到WIFI
Sep05 16:13:48连接到WIFI
Sep05 16:13:49连接到WIFI
Sep05 16:13:50连接到WIFI
Sep05 16:15:54连接到WIFI
Sep05 16:15:55连接到WIFI
Sep05 16:15:55连接到WIFI
Sep05 16:15:56连接到WIFI
Sep05 16:15:57连接到WIFI
Sep05 16:15:58连接到WIFI
Sep05 16:15:59连接到WIFI
Sep05 16:16:01连接到WIFI
答案 4 :(得分:1)
这就是它的完成方式。以下示例代码在单击提交按钮时将详细信息保存到文件中:
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();
}
}
});
希望这会有所帮助:)
答案 5 :(得分:0)
尝试更改
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(logFile, true)));
到
FileWriter fileWritter = new FileWriter(logFile,true); //true = append file
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(YourData);
bufferWritter.close();