我正在创建一个将byte[]
保存到文件中的方法。这是我正在编写的一个Java助手,所以它需要能够处理任何类型的系统。我在这个例子上看到了FileOutputStream
的方法write
,它接受byte[]
。但是我已经有了一个将输入流保存到文件中的方法。
哪一个是最好的?
/**
* 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)) > 0) {
out.write(buffer, 0, length);
}
inputStream.close();
}
}
/**
* 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);
}
显然,第二个更短更容易,但我只是想知道其中一个是否比另一个更理想。另外,作为附带说明,我想知道字节缓冲区的最佳大小。
发布于 2012-05-07 06:58:11
考虑到JVM和Java标准库中已经投入了大量的精力和精力,第二个实现将会更快,这是一个虚拟的必然。
不过,这真的有关系吗?担心优化通常只有在系统性能不足时才有用。首先要担心功能和可读性,这要重要得多。当系统接近完成时,可以解决性能问题(如果存在的话),并且可以获得关于瓶颈所在位置的实际性能数据。
参见维基百科关于程序优化的文章--特别是“何时优化”一节
https://codereview.stackexchange.com/questions/11556
复制相似问题