title: How to append/write huge data file text in Java
body: <p>I have a database with 150k records.  I want to write this to file as fast as possible.  I've tried many approaches, but all seem slow.  How do I make this faster?</p>
  
  <p>I read these records in blocks of 40k. So first I read 40k then another 40k and so on. </p>
  
  <p>After reading the records, this process returns a StringBuilder which contains 40k lines. Then we write this StringBuilder to a file.  </p>
  
  <pre><code>private static void write(StringBuilder sb, Boolean append) throws Exception {
      File file = File.createTempFile("foo", ".txt");
  
      FileWriter writer = new FileWriter(file.getAbsoluteFile(), append);
      PrintWriter out = new PrintWriter(writer);
      try {
          out.print(sb);           
          out.flush();
          writer.flush();
      } finally {
          writer.close();
          out.close();
      }
  }
  </code></pre>
  
  <p>I read this other example but it is equally slow: <a href="https://stackoverflow.com/questions/1062113/fastest-way-to-write-huge-data-in-text-file-java">Fastest way to write huge data in text file Java</a></p>
  
  <p>I also tried it with NIO api:</p>
  
  <pre><code>private static void write(StringBuilder sb, Boolean append)) throws Exception {
      FileChannel rwChannel = new FileOutputStream("textfile.txt", true).getChannel();
      ByteBuffer bb = ByteBuffer.wrap(sb.toString().getBytes("UTF-8"));
      rwChannel.write(bb);
      rwChannel.close();
  }
  </code></pre>
  
  <p>Which is the best method to write/append huge data into file?</p>