title: Low number of requests/second on process that writes files on disk
body: <p>I have a process that receives a lot of requests and i'm running some load tests using Apache Bench to find out why it's so slow (240 requests/second).</p>
  
  <p>I've isolated all points and i found what the part that is slow:</p>
  
  <pre><code>def writeEmailToFile(mailMessage:MimeMessage, outputPath:String) ={
      val baos = new ByteArrayOutputStream();
      mailMessage.writeTo(baos, Array[String]("X-Sender"))
      baos.close()
      /*
      //after i'll need to include it as first line
      val emailContent = new StringBuilder()
      emailContent.append("X-Sender: ")
      emailContent.append(mailMessage.getHeader("X-Sender")(0))
      emailContent.append(System.getProperty("line.separator"))
      emailContent.append(new String(baos.toByteArray, "UTF-8"))
      */
      val fw = new FileWriter(outputPath)
      fw.write(new String(baos.toByteArray, "UTF-8"))
      fw.flush()
      fw.close()
  }
  </code></pre>
  
  <p>This is the code after i did some optimizations but still slow - before the optimization it was 98 requests/second and now i have 240 requests/second.</p>
  
  <p>Anybody could help me how to improve this method? I'm creating a ByteArrayOutoutStream and adding X-Send again because this must the first line on file.</p>
  
  <p>Thank in advance.</p>
  
  <p>Writing bytes: 322 requests/second.</p>
  
  <pre><code>def writeEmailToFile(mailMessage:MimeMessage, outputPath:String) ={
      val baos = new ByteArrayOutputStream()
      val outputStream = new FileOutputStream(outputPath)
      mailMessage.writeTo(baos, Array[String]("X-Sender"))
      baos.writeTo(outputStream)
      outputStream.flush()
      outputStream.close()
      baos.flush()
      baos.close()
  }
  </code></pre>