首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将字节写入文件的最佳方法

将字节写入文件的最佳方法
EN

Code Review用户
提问于 2012-05-07 14:15:35
回答 1查看 3.4K关注 0票数 2

我正在创建一个将byte[]保存到文件中的方法。这是我正在编写的一个Java助手,所以它需要能够处理任何类型的系统。我在这个例子上看到了FileOutputStream的方法write,它接受byte[]。但是我已经有了一个将输入流保存到文件中的方法。

哪一个是最好的?

备选方案1

代码语言:javascript
运行
复制
/**
* 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();
  }
}

备选方案2

代码语言:javascript
运行
复制
/**
* 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);
}

显然,第二个更短更容易,但我只是想知道其中一个是否比另一个更理想。另外,作为附带说明,我想知道字节缓冲区的最佳大小

EN

回答 1

Code Review用户

回答已采纳

发布于 2012-05-07 14:58:11

考虑到JVM和Java标准库中已经投入了大量的精力和精力,第二个实现将会更快,这是一个虚拟的必然。

不过,这真的有关系吗?担心优化通常只有在系统性能不足时才有用。首先要担心功能和可读性,这要重要得多。当系统接近完成时,可以解决性能问题(如果存在的话),并且可以获得关于瓶颈所在位置的实际性能数据。

参见维基百科关于程序优化的文章--特别是“何时优化”一节

票数 6
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/11556

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档