How to use FileChannel to add one file content to the end of another file?

The a.txt file is as follows:

 ABC 

The d.txt file looks like this:

 DEF 

I am trying to take β€œDEF” and add it to β€œABC”, so a.txt looks like

 ABC DEF 

The methods I tried always overwrite the first record completely, so I always get:

 DEF 

Here are two methods I've tried:

 FileChannel src = new FileInputStream(dFilePath).getChannel(); FileChannel dest = new FileOutputStream(aFilePath).getChannel(); src.transferTo(dest.size(), src.size(), dest); 

... and I tried

 FileChannel src = new FileInputStream(dFilePath).getChannel(); FileChannel dest = new FileOutputStream(aFilePath).getChannel(); dest.transferFrom(src, dest.size(), src.size()); 

The API is unclear about the listing and passing from the parameter description here:

http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html#transferTo(long , long, java.nio.channels.WritableByteChannel)

Thanks for any ideas.

+6
source share
3 answers

Move target channel position to end:

 FileChannel src = new FileInputStream(dFilePath).getChannel(); FileChannel dest = new FileOutputStream(aFilePath).getChannel(); dest.position( dest.size() ); src.transferTo(0, src.size(), dest); 
+3
source

This is old, but the redefinition is due to the mode in which you open the file output stream. For those who need it, try

 FileChannel src = new FileInputStream(dFilePath).getChannel(); FileChannel dest = new FileOutputStream(aFilePath, true).getChannel(); //<---second argument for FileOutputStream dest.position( dest.size() ); src.transferTo(0, src.size(), dest); 
+10
source

pure nio solution

 FileChannel src = FileChannel.open(Paths.get(srcFilePath), StandardOpenOption.READ); FileChannel dest = FileChannel.open(Paths.get(destFilePath), StandardOpenOption.APPEND); // if file may not exist, should plus StandardOpenOption.CREATE long bufferSize = 8 * 1024; long pos = 0; long count; long size = src.size(); while (pos < size) { count = size - pos > bufferSize ? bufferSize : size - pos; pos += src.transferTo(pos, count, dest); // transferFrom doesn't work } // do close src.close(); dest.close(); 

However, I still have a question: why transferFrom does not work here?

+1
source

Source: https://habr.com/ru/post/958595/


All Articles