微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用FileChannel将一个文件的内容附加到另一个文件的末尾?

文件a.txt看起来像:
ABC

文件d.txt看起来像:

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 param描述:

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

谢谢你的任何想法.

解决方法

将目标通道的位置移动到结尾:
FileChannel src = new FileInputStream(dFilePath).getChannel(); 
FileChannel dest = new FileOutputStream(aFilePath).getChannel();
dest.position( dest.size() );
src.transferTo(0,dest);

原文地址:https://www.jb51.cc/java/127971.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐