我正在尝试构建自定义FileChannel
,并且由于文档不一致而导致我不清楚。
FileChannel.transferFrom(ReadableByteChannel src, long position, long count)
方法的文档说明了
如果给定位置大于文件的当前大小,则不传输任何字节。
现在,他们不应该说这个而不是吗? :
“如果
position + count
大于文件的当前大小,则不传输任何字节。”
我怀疑这可能是文档中的错误的原因是这个。在同一API文档的其他地方,如果文件需要增长,则会明确提及它,如FileChannel.write(ByteBuffer src, long position)
的情况:
“如果给定位置大于文件的当前大小,则文件将增长以容纳新字节;”
因此,如果在FileChannel.transferFrom()
的情况下没有提及任何文件增长,我会觉得文件不应该通过这种方法增长。但问题是,文件不仅会增长“如果给定的位置大于文件的当前大小”,而且“如果position + count
大于文件的当前大小“。
答案 0 :(得分:0)
和你一样documentation:
如果源通道的剩余字节数少于计数字节,或者源通道非阻塞且输入缓冲区中可立即使用的字节数少于计数字节,则将传输少于请求的字节数。
为什么transferFrom应该增长ReadableBiteChannel?
所以:否
“如果position + count大于文件的当前大小,则不传输任何字节。”
表示:
Path sourcePath = Paths.get("C:/FileChannelDemo/source.txt");
Path targetPath = Paths.get("C:/FileChannelDemo/target.txt");
Files.createDirectories(sourcePath.getParent());
BufferedWriter writer = Files.newBufferedWriter(sourcePath,
StandardCharsets.UTF_8);
// 200k
while (Files.size(sourcePath) < 200 * 1024)
writer.write(System.currentTimeMillis() + "\n");
FileChannel src = FileChannel.open(sourcePath, StandardOpenOption.READ);
FileChannel trgt = FileChannel.open(targetPath, EnumSet.of(StandardOpenOption.WRITE,
StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING));
int count = 200*1024;
System.out.println("current size is: " + Files.size(targetPath) + "smaller than count:" +count);
trgt.transferFrom(src, 0, count);
不会传输任何数据。 但确实如此。
不转移count
个字节的原因如上所述。