title: Best way to continuously write to file (50 times per second)
body: <p>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 :</p>
  
  <pre><code>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();
      }
  </code></pre>
  
  <p>ie, on every SensorEvent, you open the file, write the values, then close the file, then open it again 20 milliseconds later.</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>Thanks</p>