dou dou - 5 months ago 17
Android Question

how to write data in a file with android studio

I am trying to write a code for an application that displays the values of the magnetometer sensor and save these data in a file.
I wrote the following code but the problem is in my file I find only one line containing the last values.

FloatingActionButton fab;
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener( new View.OnClickListener(){
@Override
public void onClick(View view){
final Thread t = new Thread() {
File openfilename= new File(Environment.getExternalStorageDirectory(),"myfile.txt");
FileOutputStream f;
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(500);
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView tv;
tv=(TextView)findViewById(R.id.tv);

tv.setText(" x="+Float.toString(xx)+" y="+Float.toString(yy)+" z="+Float.toString((zz))+" Puissance="+Float.toString(magneticStrenght));

try {
FileOutputStream f =new FileOutputStream(openfilename);

PrintWriter pw=new PrintWriter(f);
pw.append("\n x="+Float.toString(xx)+" y="+Float.toString(yy)+" z="+Float.toString((zz))+" Puissance="+Float.toString(magneticStrenght));
//close the file
pw.flush();
pw.close();
f.close();

} catch (java.io.IOException e) {
//do something if an IOException occurs.
Log.e("Exception", "File write failed: " + e.toString());
}
}
});
}
} catch (InterruptedException e) {
}
}
};

t.start();


Can you please try to help and see what is wrong with my code.

Answer

You should open the FileOutputStream in append mode, by passing a boolean true as the second parameter

FileOutputStream f = new FileOutputStream(openfilename, true);

See this for more details