有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaNIO文件通道。从转移0开始转移?

我正在尝试使用NIO,使用transferFrom,将几个较小的文件组合成一个文件

对transferFrom的调用返回0。也不例外。没有采取任何措施来启用同步行为

    FileOutputStream fos = new FileOutputStream(path);
    FileChannel fileBeingAssembled = fos.channel();
    int progressiveOffset = 4096;
    FileInputStream fis = new FileInputStream(tmpT5);
    FileChannel channel = fis.getChannel();
    channel.position(0);
    int thisItemLength = (int)channel.size();
    LOG.info("Writing " + tag + " at " + progressiveOffset + " length " + thisItemLength);
    fileBeingAssembled.position(progressiveOffset);
    long x = fileBeingAssembled.transferFrom(channel, progressiveOffset, thisItemLength);
    LOG.info("transferred " + x);
    progressiveOffset += thisItemLength;

日志示例:

4409 [main] INFO  com.basistech.seg.writing.ModelOutputTask  - available 1856216
4409 [main] INFO  com.basistech.seg.writing.ModelOutputTask  - Writing word at 15024620 length 1856216
4419 [main] INFO  com.basistech.seg.writing.ModelOutputTask  - transferred 0

共 (1) 个答案

  1. # 1 楼答案

    两个最明显的答案是:

    1. tmpT5指向零字节文件,或
    2. 路径指向的文件长度小于4096字节

    transferFrom文档:

    If the given position is greater than the file's current size then no bytes are transferred.