我有一个10GB的大文件, 如果我使用 java 中的 readively() 读取其全部内容,则会出现内存不足错误, 所以我决定使用相同的 readively() 来读取 10gb 大文件,为此我需要为 readively() 传递偏移量和长度参数。偏移量必须是 long 或 double 数据类型,以便它可以指向文件的不同部分。但 readively() 只接受 int 偏移量。如何读取大数据?
try {
IOUtils.readFully(in, contents, minOffset, maxOffset);
value.set(contents, 0, contents.length);
} finally {
IOUtils.closeStream(in);
}
我可以使用 seek()
到达特定位置,然后从该位置使用 readously()
吗?
最佳答案
使用类 java.util.Scanner 运行文件的内容并逐行串行检索行:
FileInputStream inputStream = null;
Scanner sc = null;
try {
inputStream = new FileInputStream(path);
sc = new Scanner(inputStream, "UTF-8");
while (sc.hasNextLine()) {
String line = sc.nextLine();
// System.out.println(line);
}
// note that Scanner suppresses exceptions
if (sc.ioException() != null) {
throw sc.ioException();
}
}
finally {
if (inputStream != null) {
inputStream.close();
}
if (sc != null) {
sc.close();
}
}
此解决方案将迭代文件中的所有行 - 允许处理每一行 - 而不保留对它们的引用 - 最后,不将它们保留在内存中。欲了解更多详情,请参阅this .
关于java - Java中使用readly读取大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24211078/