Java - File To Byte Array - Fast One

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.

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

Answers


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.


apache commons-io FileUtils.readFileToByteArray


Need Your Help

Function Import repeats same row

.net entity-framework

I am using entity framework to access my data on MSSQL server. I call a stored procedure via function import. When I iterate through the rows of returned data, the rows are all the same as the fi...

Inserting string with commas sqlplus

sql string oracle sqlplus

I'm unable to get a string into my table that has commas, is my datatype incorrect? I've been battling this and can't find an answer anywhere online lol.