我有一个(可能很长)的二进制文件列表,我希望能够惰性地读取它们。由于文件太多而无法加载到内存中,因此我目前将它们作为MappedByteBuffer使用FileChannel.map()
进行了读取,但这可能并不是必需的。我希望readBinaryFiles(...)
方法返回一个Java 8 Stream,以便在访问它们时可以惰性加载文件列表。
public List<FileDataMetaData> readBinaryFiles(
List<File> files,
int numDataPoints,
int dataPacketSize )
throws
IOException {
List<FileDataMetaData> fmdList = new ArrayList<FileDataMetaData>();
IOException lastException = null;
for (File f: files) {
try {
FileDataMetaData fmd = readRawFile(f, numDataPoints, dataPacketSize);
fmdList.add(fmd);
} catch (IOException e) {
logger.error("", e);
lastException = e;
}
}
if (null != lastException)
throw lastException;
return fmdList;
}
// The List<DataPacket> returned will be in the same order as in the file.
public FileDataMetaData readRawFile(File file, int numDataPoints, int dataPacketSize) throws IOException {
FileDataMetaData fmd;
FileChannel fileChannel = null;
try {
fileChannel = new RandomAccessFile(file, "r").getChannel();
long fileSz = fileChannel.size();
ByteBuffer bbRead = ByteBuffer.allocate((int) fileSz);
MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileSz);
buffer.get(bbRead.array());
List<DataPacket> dataPacketList = new ArrayList<DataPacket>();
while (bbRead.hasRemaining()) {
int channelId = bbRead.getInt();
long timestamp = bbRead.getLong();
int[] data = new int[numDataPoints];
for (int i=0; i<numDataPoints; i++)
data[i] = bbRead.getInt();
DataPacket dp = new DataPacket(channelId, timestamp, data);
dataPacketList.add(dp);
}
fmd = new FileDataMetaData(file.getCanonicalPath(), fileSz, dataPacketList);
} catch (IOException e) {
logger.error("", e);
throw e;
} finally {
if (null != fileChannel) {
try {
fileChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return fmd;
}
从readBinaryFiles(...)
返回fmdList.Stream()
并不能实现这一点,因为文件内容已经被读入内存,我将无法做到惰性读取。
其他读取多个文件内容作为Stream的方法都依赖于使用Files.lines()
,但我需要读取二进制文件。
如果Scala或golang对此用例有更好的支持,我也可以考虑使用它们来实现。
我希望能够获得有关如何惰性读取多个二进制文件内容的任何指针。
return files.stream().map(f -> readRawFile(f, numDataPoints, dataPacketSize))
就足够了。您可以让该方法在内部捕获IOException并将其包装在UncheckedIOException中。(延迟执行的问题在于异常也需要被延迟处理。) - VGRread
所做的。 - Holger