Java 如何使用FileChannel附加一个文件';是否将内容放在另一个文件的末尾?

Java 如何使用FileChannel附加一个文件';是否将内容放在另一个文件的末尾?,java,Java,文件a.txt看起来像: ABC DEF 文件d.txt看起来像: ABC DEF 我试图获取“DEF”并将其附加到“ABC”中,因此a.txt看起来像 ABC DEF 我尝试的方法总是完全覆盖第一个条目,因此我总是以以下方式结束: DEF 以下是我尝试过的两种方法: FileChannel src = new FileInputStream(dFilePath).getChannel(); FileChannel dest = new FileOutputStream(aFile

文件
a.txt
看起来像:

ABC
DEF
文件
d.txt
看起来像:

ABC
DEF
我试图获取“DEF”并将其附加到“ABC”中,因此
a.txt
看起来像

ABC
DEF
我尝试的方法总是完全覆盖第一个条目,因此我总是以以下方式结束:

DEF
以下是我尝试过的两种方法:

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

src.transferTo(dest.size(), src.size(), dest);
…我已经试过了

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

dest.transferFrom(src, dest.size(), src.size());
API不清楚此处的transferTo和transferFrom参数描述:

,long,java.nio.channels.WritableByteChannel)


谢谢你的建议。

将目标频道的位置移到末尾:

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

这是旧的,但由于打开文件输出流的模式,会发生重写。 如果有人需要,试试看

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);
filechannelsrc=newfileinputstream(dFilePath).getChannel();
FileChannel dest=newfileoutputstream(aFilePath,true).getChannel()// 纯nio溶液

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();
FileChannel src=FileChannel.open(path.get(srcFilePath),StandardOpenOption.READ);
FileChannel dest=FileChannel.open(path.get(destFilePath),StandardOpenOption.APPEND);//如果文件可能不存在,则应加上StandardOpenOption.CREATE
长缓冲区大小=8*1024;
长pos=0;
长计数;
长尺寸=src.size();
while(pos缓冲大小?缓冲大小:大小-位置;
pos+=src.transferTo(pos,count,dest);//transferFrom不工作
}
//关闭
src.close();
dest.close();
然而,我仍然有一个问题:为什么transferFrom在这里不起作用