Java - 文件到字节数组 - 快速一

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11741804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:12:19  来源:igfitidea点击:

Java - File To Byte Array - Fast One

java

提问by alessandro

I want to read a file into a byte array. So, I am reading it using:

我想将文件读入字节数组。所以,我正在阅读它:

    int len1 = (int)(new File(filename).length());
    FileInputStream fis1 = new FileInputStream(filename);
    byte buf1[] = new byte[len1];
    fis1.read(buf1);

However, it is realy very slow. Can anyone inform me a very fast approach (possibly best one) to read a file into byte array. I can use java library also if needed.

然而,它真的很慢。谁能告诉我一种非常快速的方法(可能是最好的方法)将文件读入字节数组。如果需要,我也可以使用 java 库。

Edit: Is there any benchmark which one is faster (including library approach).

编辑:是否有任何基准测试哪个更快(包括库方法)。

回答by AlexR

It is not very slow, at least there is not way to make it faster. BUT it is wrong. If file is big enough the method read()will not return all bytes from fist call. This method returns number of bytes it managed to read as return value.

它不是很慢,至少没有办法让它更快。但这是错误的。如果文件足够大,该方法read()将不会从第一次调用中返回所有字节。此方法返回它设法读取的字节数作为返回值。

The right way is to call this method in loop:

正确的方法是在循环中调用这个方法:

  public static void copy(InputStream input,
      OutputStream output,
      int bufferSize)
      throws IOException {
    byte[] buf = new byte[bufferSize];
    int bytesRead = input.read(buf);
    while (bytesRead != -1) {
      output.write(buf, 0, bytesRead);
      bytesRead = input.read(buf);
    }
    output.flush();
  }

call this as following:

调用如下:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
copy(new FileInputStream(myfile), baos);
byte[] bytes = baos.toByteArray();

Something like this is implemented in a lot of packages, e.g. FileUtils.readFileToByteArray()mentioned by @Andrey Borisov (+1)

很多包中都实现了这样的东西,例如FileUtils.readFileToByteArray()@Andrey Borisov (+1) 提到的

EDIT

编辑

I think that reason for slowness in your case is the fact that you create so huge array. Are you sure you really need it? Try to re-think your design. I believe that you do not have to read this file into array and can process data incrementally.

我认为在您的情况下缓慢的原因是您创建了如此庞大的数组。你确定你真的需要它吗?尝试重新思考您的设计。我相信您不必将此文件读入数组,并且可以增量处理数据。

回答by Andrey Borisov

apache commons-io FileUtils.readFileToByteArray

apache commons-io FileUtils.readFileToByteArray