Optimal method for writing bytes to file I'm making a method to save a byte[] to a file. It's for a Java Helper I'm writing, so it needs to be able to handle any kind of system. I saw on this example the method of FileOutputStream called write which accepts a byte[]. But I already have a method which will save an input stream to a file.

Which is best?

Alternative 1

/**
* Saves the given bytes to the output file.
*
* @param bytes
* @param outputFile
* @throws FileNotFoundException
* @throws IOException
*/
public static void saveBytesToFile(byte[] bytes, File outputFile) throws FileNotFoundException, IOException {
  ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
  saveInputStream(inputStream, outputFile);
}

/**
* Saves the given InputStream to a file at the destination. Does not check whether the destination exists.
*
* @param inputStream
* @param destination
* @throws FileNotFoundException
* @throws IOException
*/
public static void saveInputStream(InputStream inputStream, File outputFile) throws FileNotFoundException, IOException {
  try (OutputStream out = new FileOutputStream(outputFile)) {
    byte[] buffer = new byte[2097152];
    int length;
    while ((length = inputStream.read(buffer)) &gt; 0) {
      out.write(buffer, 0, length);
    }
    inputStream.close();
  }
}


Alternative 2

/**
* Saves the given bytes to the output file.
*
* @param bytes
* @param outputFile
* @throws FileNotFoundException
* @throws IOException
*/
public static void saveBytesToFile2(byte[] bytes, File outputFile) throws FileNotFoundException, IOException {
  FileOutputStream out = new FileOutputStream(outputFile);
  out.write(bytes);
}


Obviously the second is shorter and easier, but I'm just wondering whether one's more optimal than the other. Also, as a side note, I'm wondering about the optimal size for the byte buffer.
Given the care and effort that has been put into performance within the JVM and Java standard libraries, it is a virtual certainty that the second implementation will be faster.

However, does it really matter? Worrying about optimization is generally only useful if the system performance is inadequate. It's far more important to worry about functionality and readability first. Performance issues can be tackled (if they exist) when the system is nearing completion and it is possible to get actual performance data on where the bottlenecks are.

See the Wikipedia article on Program Optimization - especially the "When to optimize" section