【发布时间】:2023-04-11 12:39:02
【问题描述】:
我有大于 4GB 的大型机数据文件。我需要每 500 个字节读取和处理数据。我曾尝试使用 FileChannel,但收到消息 Integer.Max_VALUE 已超出错误
public void getFileContent(String fileName) {
RandomAccessFile aFile = null;
FileChannel inChannel = null;
try {
aFile = new RandomAccessFile(Paths.get(fileName).toFile(), "r");
inChannel = aFile.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(500 * 100000);
while (inChannel.read(buffer) > 0) {
buffer.flip();
for (int i = 0; i < buffer.limit(); i++) {
byte[] data = new byte[500];
buffer.get(data);
processData(new String(data));
buffer.clear();
}
}
} catch (Exception ex) {
// TODO
} finally {
try {
inChannel.close();
aFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
你能帮我解决一下吗?
【问题讨论】:
-
显示异常和堆栈跟踪
-
您可以尝试用
BufferedInputStream包裹FileInputStream。 -
看看这个 -> stackoverflow.com/questions/8076472/… 会给你一个关于你遇到的错误的想法
-
顺便说一句,考虑使用try-with-resources,对于可关闭的资源管理更方便
-
如果您要解析字符,为什么不直接使用阅读器?例如,
try (BufferedReader reader = Files.newBufferedReader(Paths.get(fileName))) { … }