title: Most efficient way to write a byte matrix to text file
body: <p>I have a problem in Java writing a 3D byte matrix (as unsigned bytes) to a text file.
  The matrix is 3D and looks like <code>wMatrix3D[k][j][i]</code>. I want to it to a textfile so the values are separated by white space and a new line break every 1,000 values (there are 1,000 pixel values per row and 1,000 rows making a 1,000 x 1,000 text file representing an image).</p>
  
  <p>Currently, I do it like this:</p>
  
  <pre><code>BufferedWriter out = new BufferedWriter(new FileWriter(imgout));
  
  //Parse Headers
  for(int countHeaderLines = 0; countHeaderLines &lt; numHeaders; countHeaderLines+=1){
      out.write(headers[countHeaderLines] + "\n");
  }
  System.out.println("Wrote Headers");
  
  //Parse 1,000,000 x 1,000 2D matrix into 3D (1,000 x 1,000) x 1,000 matrix 
  System.out.println("Writing main matrix to text...");
  
  //String slice = new String();
  for(int k = 0; k &lt; numLayers; k++){
      for(int j = 0;  j &lt; numRows; j++){
          String rowStr = new String();
          for(int i = 0; i &lt; numColumns; i++){
              rowStr += Integer.toString((Integer.valueOf(wMatrix3D[k][j][i]) &amp; 0xFF)) + " ";
          }
      out.write(rowStr + "\n");
      }
  
  /*if( (k+1) % 5 == 0){
  slice = new String();
  out.write(slice);
  System.out.println("Writing Set of 10:" + k);
  }*/
  
  System.out.println("k: " + k);
  }
  </code></pre>
  
  <p>However, this way is VERY VERY slow. is there a more efficient way to do this? In C I have no problem using "fprintf" but in Java I just cannot get it to work well.</p>