Search code examples
androidoutputstream

android output log but I cant output multi line


I have problem that I have write an android program. I want to save users input to log. but,no matter what I do.I only can save one line. the new data will cover old data when I press the button. How I can do to save data and not to cover it?

this is my code,mainactivity.java

public class MainActivity extends AppCompatActivity {
private EditText acc;
private Button login;
private Write write = new Write(MainActivity.this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   login = (Button)findViewById(R.id.login);
 acc=(EditText)findViewById(R.id.acc);
 login.setOnClickListener(getDBRecord);

}

private Button.OnClickListener getDBRecord = new Button.OnClickListener() {
    public void onClick(View v) {
     String car_num=acc.getText().toString().toUpperCase();
           write.WriteFileExample(car_num);
    }
};

}

and this is my code ,write.java

public class Write {
private static Context context;

public Write(Context context) {
    this.context = context;
}

public static void WriteFileExample(String message) {
    FileOutputStream fop = null;
    File file;
    String content = message;

    try {
        File sdcard = Environment.getExternalStorageDirectory();

        file = new File(sdcard, "myLog.log"); //輸出檔案位置

        if (!file.exists()) { // 如果檔案不存在,建立檔案
            file.createNewFile();
        }
       fop =new  FileOutputStream(file);
        byte[] contentInBytes = content.getBytes();// 取的字串內容bytes

        fop.write(contentInBytes); //輸出

    } catch (IOException e) {} 
    finally {
        try {
            if (fop != null) 
                fop.close();
            } catch (IOException e) {}
    }
}
}

thanks


Solution

  • replace

    fop =new  FileOutputStream(file);
    

    with

    fop =new  FileOutputStream(file, true);
    

    The second parameter is the append option. By setting it true, you will be appending the new content to the old content rather than overwriting over the old content.