How do I use filechannel to append the contents of one file to the end of another?
•
Java
The file a.txt looks like:
ABC
The file d.txt looks like: @ h_ 404_ 5@
DEF
I'm trying to take "def" and attach it to "ABC", so a.txt looks like @ H_ 404_ 5@
ABC DEF
The method I tried always completely overwrites the first entry, so I always end up with: @ h_ 404_ 5@
DEF
Here are two methods I have tried: @ h_ 404_ 5@
FileChannel src = new FileInputStream(dFilePath).getChannel(); FileChannel dest = new FileOutputStream(aFilePath).getChannel(); src.transferTo(dest.size(),src.size(),dest);
... I tried @ H_ 404_ 5@
FileChannel src = new FileInputStream(dFilePath).getChannel(); FileChannel dest = new FileOutputStream(aFilePath).getChannel(); dest.transferFrom(src,dest.size(),src.size());
API unclear transferto and transferfrom param Description: @ h_ 404_ 5@
http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html#transferTo (long,long,java.nio.channels.WritableByteChannel)@H_ 404_ 5@
Thank you for any ideas@ H_ 404_ 5@
Solution
Move the position of the target channel to the end:
FileChannel src = new FileInputStream(dFilePath).getChannel(); FileChannel dest = new FileOutputStream(aFilePath).getChannel(); dest.position( dest.size() ); src.transferTo(0,dest);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码