读取文件列表作为 Java 8 流

Reading a list of Files as a Java 8 Stream

我有一个(可能很长)二进制文件列表,我想懒惰地阅读它们。将有太多文件加载到内存中。我目前正在将它们作为 FileChannel.map() 的 MappedByteBuffer 来读取,但这可能不是必需的。我想要方法 readBinaryFiles(...) 到 return a 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 中做这件事,如果这些语言比 Java 对这个用例有更好的支持。

对于如何延迟读取多个二进制文件内容的任何指示,我将不胜感激。

我不知道这有多高效,但您可以使用 DataInputStream 包裹的 java.io.SequenceInputStream。这将有效地将您的文件连接在一起。如果你从每个文件创建一个 BufferedInputStream,那么整个事情应该被适当地缓冲。

在 中读取 文件是不可能有惰性的,因为您正在读取整个文件以构建 FileDataMetaData 的实例。您需要对该 class 进行大量重构,以便能够构建 FileDataMetaData 的实例而无需读取整个文件。

但是,该代码中有几处需要清理,甚至特定于 Java 7 而不是 Java 8,即您不需要 RandomAccessFile 绕道再打开一个频道,有 try-with-resources 来确保正确关闭。请进一步注意,您使用内存映射没有任何意义。映射文件后将全部内容复制到堆ByteBuffer中时,没有什么偷懒的。这与在通道上使用堆 ByteBuffer 调用 read 时发生的情况完全相同,只是 JRE 可以在 read 情况下重用缓冲区。

为了让系统管理页面,您必须从映射的字节缓冲区中读取。根据系统的不同,这可能仍然不比将小块重复读入堆字节缓冲区更好。

public FileDataMetaData readRawFile(
    File file, int numDataPoints, int dataPacketSize) throws IOException {

    try(FileChannel fileChannel=FileChannel.open(file.toPath(), StandardOpenOption.READ)) {
        long fileSz = fileChannel.size();
        MappedByteBuffer bbRead=fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileSz);
        List<DataPacket> dataPacketList = new ArrayList<>();
        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();
            dataPacketList.add(new DataPacket(channelId, timestamp, data));
        }
        return new FileDataMetaData(file.getCanonicalPath(), fileSz, dataPacketList);
    } catch (IOException e) {
        logger.error("", e);
        throw e;
    }
}

基于此方法构建 Stream 非常简单,只需处理已检查的异常:

public Stream<FileDataMetaData> readBinaryFiles(
    List<File> files, int numDataPoints, int dataPacketSize) throws IOException {
    return files.stream().map(f -> {
        try {
            return readRawFile(f, numDataPoints, dataPacketSize);
        } catch (IOException e) {
            logger.error("", e);
            throw new UncheckedIOException(e);
        }
    });
}

基于,我认为他的基本解决方案是:

return files.stream().map(f -> readRawFile(f, numDataPoints, dataPacketSize))

是正确的,因为它会懒惰地处理文件(如果根据 map() 操作的结果调用短路终端操作,它将停止。我还建议与 readRawFile 的实现略有不同利用 try with resources 和 InputStream,不会将整个文件加载到内存中:

public FileDataMetaData readRawFile(File file, int numDataPoints, int dataPacketSize)
  throws DataPacketReadException { // <- Custom unchecked exception, nested for class

  FileDataMetadata results = null;

  try (FileInputStream fileInput = new FileInputStream(file)) {
    String filePath = file.getCanonicalPath();
    long fileSize = fileInput.getChannel().size()

    DataInputStream dataInput = new DataInputStream(new BufferedInputStream(fileInput);

    results = new FileDataMetadata(
      filePath, 
      fileSize,
      dataPacketsFrom(dataInput, numDataPoints, dataPacketSize, filePath);
  }

  return results;
}

private List<DataPacket> dataPacketsFrom(DataInputStream dataInput, int numDataPoints, int dataPacketSize, String filePath)
    throws DataPacketReadException { 

  List<DataPacket> packets = new 
  while (dataInput.available() > 0) {
    try {
      // Logic to assemble DataPacket
    }
    catch (EOFException e) {
      throw new DataPacketReadException("Unexpected EOF on file: " + filePath, e);
    }
    catch (IOException e) {
      throw new DataPacketReadException("Unexpected I/O exception on file: " + filePath, e);
    }
  }

  return packets;
}

这应该会减少代码量,并确保您的文件在出现错误时关闭。

这应该足够了:

return files.stream().map(f -> readRawFile(f, numDataPoints, dataPacketSize));

…如果,也就是说,您愿意从 readRawFile 方法的签名中删除 throws IOException。您可以让该方法在内部捕获 IOException 并将其包装在 UncheckedIOException 中。 (延迟执行的问题是异常也需要延迟。)