小编典典

将字符串写入文本文件

java

我将日志保存到sdcard上的.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());
    }
}

在恢复中挂载/ data后,/ sdcard和/ data / media /
0中的日志文件会显示完整的日志历史记录,但在设备开机时不会显示完整的日志历史记录


阅读 210

收藏
2020-11-30

共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();
                    }
            }
        });

希望这可以帮助 :)

2020-11-30