连续写入文件的最佳方法(每秒50次) [英] Best way to continuously write to file (50 times per second)

查看:259
本文介绍了连续写入文件的最佳方法(每秒50次)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个Android应用程序,它将加速度计和陀螺仪数据记录到一个文本文件中.在大多数教程中,他们使用一种方法来创建两个文本文件,然后每秒分别打开和关闭它们50次.即:

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();
    }

即,在每个SensorEvent上,打开文件,写入值,然后关闭文件,然后在20毫秒后再次打开它.

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

一切似乎都很好,我只是想知道是否有更好的方法来做到这一点?我尝试使用布尔值标志进行一些更改,以说说流是否已打开,然后如果标志设置为true,则使用不同的writeToFile,但显然fileOutputStream有时可以在20毫秒的时间范围内自行关闭,并且应用程序崩溃

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.

谢谢

推荐答案

这不是一个好方法.更好的方法是一次创建FileOutputStream,将其保存为该类的实例成员,然后对其进行写入(可能偶尔调用flush以确保将其写入磁盘).

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).

这篇关于连续写入文件的最佳方法(每秒50次)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆