Continuously Save and Auto Increment String Values to File - Android

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-13 02:36:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!