Best way to continuously write to file (50 times per second)

不打扰是莪最后的温柔 提交于 2020-01-07 06:42:19

问题


I am building an Android app which records Accelerometer and Gyroscope data to a text file. In most of the tutorials they use a method which involves creating two text files, and opening and closing them each 50 times per second. ie :

private static void writeToFile(File file, String data) {

    FileOutputStream stream = null;

    try {

        stream = new FileOutputStream(file, true);
        stream.write(data.getBytes());
    } catch (FileNotFoundException e) {
        Log.e("History", "In catch");
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();

    try {

        stream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

ie, on every SensorEvent, you open the file, write the values, then close the file, then open it again 20 milliseconds later.

It all seems to be working fine, I was just wondering if there was a better way of going about doing it? I tried some changes using a boolean flag to say whether the stream is already open or not, and then a different writeToFile if flag is set to true, but clearly the fileOutputStream can sometimes close itself in the 20 millisecond time frame, and the app crashes.

So I guess my Question is: How many system resources does it take to open, write and close a file that many times? Is it fine, and not something I should worry about, or is there a better way of doing things? Bear in mind continous sensor logging already takes a toll on battery life, so I would like to do things as efficiently as possible.

Thanks


回答1:


It's not a good way of doing it. A better way would be to create the FileOutputStream once, save it as an instance member of whatever class this is, and just write to it (possibly with an occasional call to flush to make sure it writes to disk).



来源:https://stackoverflow.com/questions/46720634/best-way-to-continuously-write-to-file-50-times-per-second

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