Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte[] and java.lang.OutOfMemoryError reading file by bits

I am trying to write a reader which reads files by bits but I have a problem with large files. I tried to read file with 100 mb and it took over 3 minutes but it worked.

However, then I tried file with 500 mb but it didn't even started. Because of this line:

byte[] fileBits = new byte[len];

Now I am searching for sulutions and can't find any. Maybe someone had solved it and could share some code, tips or idea.

if (file.length() > Integer.MAX_VALUE) {
    throw new IllegalArgumentException("File is too large: " + file.length());
}

int len = (int) file.length();
FileInputStream inputStream = new FileInputStream(file);

try {
    byte[] fileBits = new byte[len];
    for (int pos = 0; pos < len;) {
        int n = inputStream.read(fileBits, pos, len - pos);
        if (n < 0) {
            throw new EOFException();
        }
        pos += n;
    }

inputStream.read(fileBits, 0, inputStream.available());
inputStream.close();
like image 270
Streetboy Avatar asked Feb 29 '12 19:02

Streetboy


1 Answers

I suggest you try memory mapping.

FileChannel fc = new FileInputStream(file).getChannel();
MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, (int) fc.size());

This will make the whole file available almost immediately (about 10 ms) and uses next to no heap. BTW The file has to be less than 2 GB.

like image 165
Peter Lawrey Avatar answered Oct 11 '22 14:10

Peter Lawrey