问题
I have code which saves a String to a file. The problem is that the String is constantly changing (as they are sensor values) but the string is only saved once, then seems to delete the file once closed and open and new one to which it prints only one value. I need it to save each value to the same file, while auto-incrementing to avoid losing any data.
Here is my code:
UPDATED: I have updated this code to the working version. The code now saves the string to the file, then updates the file each time. Thanks to @Sergii for the help!
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo_opengl_acc);
getActionBar().setTitle(R.string.title_demo_accelerometer);
viewText = (TextView) findViewById(R.id.text);
renderer = new OpenGLRenderer();
final GLSurfaceView view = (GLSurfaceView) findViewById(R.id.gl);
view.setRenderer(renderer);
}
@Override
public void onDataRecieved(TiSensor<?> sensor, String text) {
if (sensor instanceof TiAccelerometerSensor) {
try {
BufferedWriter writer =
new BufferedWriter(new FileWriter("/sdcard/test.txt", <> true));
writer.write(text);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("test", true)));
out.println(text);
out.close();
} catch (IOException e) {
//error message here or whatever...
}
}
final TiAccelerometerSensor accSensor = (TiAccelerometerSensor) sensor;
float[] values = accSensor.getData();
renderer.setRotation(values);
viewText.setText(text);
}
}
I would like to be able to open the file and see all of the values.
Thanks.
回答1:
new FileWriter("/sdcard/acvalues.txt", true)
http://developer.android.com/reference/java/io/FileWriter.html#FileWriter(java.io.File, boolean)
The parameter append determines whether or not the file is opened and appended to or just opened and overwritten.
Also: How to append text to an existing file in Java
来源:https://stackoverflow.com/questions/19864200/continuously-save-and-auto-increment-string-values-to-file-android