0

I tried to use FileChannel.transferFrom to move some content of a file to the begining.

try (RandomAccessFile rafNew = new RandomAccessFile(_fileName, "rw");
        RandomAccessFile rafOld = new RandomAccessFile(_fileName, "r");) 
{
        rafOld.seek(pos);
        rafOld.getChannel().transferTo(0, count, rafNew.getChannel());
} catch (IOException e) {
        throw new RuntimeException(e.getMessage());
}

The result of this is a file with strange repetitions of data. The example works if I first transfer data to a buffer file and then from buffer file back to the origin file again.

The Java Docs say nothing about the case where source and destination are the same file.

Marcin Król
  • 1,555
  • 2
  • 16
  • 31
  • Problem is not in this that source and destination are the same, but java operations on stream don't allow to append a content on the top of file. [link](http://stackoverflow.com/questions/6127648/writing-in-the-beginning-of-a-text-file-java) – dpolaczanski Apr 16 '14 at 20:44
  • @dpolaczanski There are no streams here, and your link doesn't say what you claim it says. – user207421 Apr 16 '14 at 22:13
  • The JavaDoc for the FileChannel class actually says that bytes can be transferred from a file to some _other_ channel, and vice versa. – Alexey Gavrilov Apr 16 '14 at 22:22
  • @EJP, I just wanted higlight that there is no mechanism which allows to append with shift data on the top. If stream can't do it, channel definetly will not do this as well – dpolaczanski Apr 17 '14 at 19:31

1 Answers1

0

You are transferring 'count' bytes starting from zero from 'rafOld' to 'rafNew', which hasn't had any seeks done on it, so is also at position zero. So at best your code doesn't do what you said it does. The seek() you did on 'rafOld' doesn't affect the transferTo() operation. You should have removed it and written

transferTo(pos, count, rafNew.getChannel());

But there are still two problems with this.

  1. If count > pos you will be overwriting the source region.

  2. transferTo() must be called in a loop, as it isn't guaranteed to compete the entire transfer in a single call. It returns the number of bytes actually transferred,

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Why is it a problem to overwrite the source region. It should be no problem if the region you are writing to is no longer in use. I mean, the more the target moves forward the more the source does, so they never overlap. – Marcin Król Apr 16 '14 at 23:23