2

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

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

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

编辑:有没有更快的基准(包括库方法)。

4

2 回答 2

16

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.

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)

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.

于 2012-07-31T14:03:16.137 回答
10

apache commons-io FileUtils.readFileToByteArray

于 2012-07-31T13:58:27.443 回答