0

I'm trying to build a custom FileChannel, and I'm experiencing a lack of clarity due to inconsistency in the documentation.

The documentation for the FileChannel.transferFrom(ReadableByteChannel src, long position, long count) method says,

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

Now, shouldn't they have said this instead? :

"If position + count is greater than file's current size then no bytes are transferred."

The reason I suspect this may be a bug in the documentation is this. Elsewhere in the same API doc, if the file needs to grow, an explicit mention of it is made, as in the case of FileChannel.write(ByteBuffer src, long position):

"If the given position is greater than the file's current size then the file will be grown to accommodate the new bytes;"

So, if no mention has been made of any file growth in case of FileChannel.transferFrom(), I get the impression that file is not supposed to grow via this method. But the problem is, the file can grow not only "If the given position is greater than the file's current size" but also "if position + count is greater than file's current size".

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Harry
  • 3,684
  • 6
  • 39
  • 48

1 Answers1

0

Same documentation as you:

Fewer than the requested number of bytes will be transferred if the source channel has fewer than count bytes remaining, or if the source channel is non-blocking and has fewer than count bytes immediately available in its input buffer.

And why should transferFrom grow the ReadableBiteChannel?

So: No

Edit 1:

"If position + count is greater than file's current size then no bytes are transferred."

means that:

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);

wouldn't transfer any data. But it does.

Reasons not to transfer countbytes are stated above.

Franz Ebner
  • 4,951
  • 3
  • 39
  • 57
  • My question is about the destination `FileChannel` on which `transferFrom` is being invoked... where the bytes from the source will go. I'm not seeking clarifications on the source channel. – Harry Jan 03 '14 at 05:24