我正在尝试编写一个按位读取文件的读取器,但是大文件有问题。我试图读取100 mb的文件,它花了3分钟多的时间,但是仍然有效。
但是,然后我尝试使用500 mb的文件,但它甚至没有启动。由于这一行:
byte[] fileBits = new byte[len];
现在,我正在寻找解决方案,但找不到任何解决方案。也许有人解决了它,可以分享一些代码,技巧或想法。
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();
我建议您尝试使用内存映射。
FileChannel fc = new FileInputStream(file).getChannel();
MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, (int) fc.size());
这将使整个文件几乎立即可用(大约10毫秒),并且几乎没有堆使用。BTW文件必须小于2 GB。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句