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();
I suggest you try memory mapping.
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.