我正在尝试为显示磁力计传感器值并将这些数据保存在文件中的应用程序编写代码。 我写了下面的代码,但问题出在我的文件中,我发现只有一行包含最后的值。如何使用android studio写入文件中的数据
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();
能不能请你帮忙看看有什么错我的代码。
事实上,我想每500ms保存一次磁力仪的值,这就是为什么我有循环 – dou