title: how to write header line only once in file in java
body: <p>I have created multiple threads using executor service in java.
  On any error during the execution of these threads, I want to write some stuff to a file. So basically I maintain one file to maintain error messages of the treads.</p>
  
  <p>I want to place a header line to this file only once as the first line.</p>
  
  <p>Here is how my code currently looks like:</p>
  
  <pre><code>catch(exception e){
      String csv = "/tmp/data1.csv";
      FileWriter writer;
      try {
          File csvFile = new File(csv);
          writer = new FileWriter(csvFile,true);
  
          if(!flag) {
              flag = true;
              for(int i=0; i&lt;metaInfo.length; i++){
                  writer.append(metaInfo[i]);
                  if(i != metaInfo.length-1)
                      writer.append(',');
              }
              writer.append('\n');
          }
          for (String aLine : line) {
              writer.append(aLine);
              writer.append(',');
          }
          writer.append(e.getMessage());
          writer.append('\n');
          writer.flush();
          writer.close();
      } catch (IOException e1) {
          e1.printStackTrace();
      }
  }
  </code></pre>
  
  <p>I am maintaining a flag to write a header line only once.
  Now I am able to place header line only once into a file.
  But as I am running many threads in parallel,I some times see the header is not placed the first line but at different positions.</p>
  
  <p>What would be the way to solve this problem?</p>