2013-11-21 13 views
6

ファイルa.txtは、次のようになります。私は "DEF" を取ると "ABC" はそうa.txtFileChannelを使用してファイルの内容を別のファイルの末尾に追加するにはどうすればよいですか?

ABC 
DEF 
のように見えるためにそれを追加しようとしている

DEF 

:よう

ABC 

ファイルd.txtが見えます

私が試した方法は、最初のエントリを常に完全に上書きするので、私はいつも最後に終わります:

01ここで
DEF 

私が試した2つの方法です:

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

src.transferTo(dest.size(), src.size(), dest); 

...と私はAPIがここtransferToとtransferFromのparamの説明については不明である

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

dest.transferFrom(src, dest.size(), src.size()); 

を試してみました:

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

ありがとうございます。

答えて

3

最後まで先チャネルの移動位置:

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

これは古いですが、オーバーライドがあるため、あなたのファイル出力ストリームをオープンモードが原因で発生します。 これを必要とする人にとって、

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); 
+1

これは受け入れられる回答である必要があります。 –

1

純粋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(); 

は、しかし、私はまだ疑問を持ってみてください:なぜtransferFromはここで働いていないのですか?

関連する問題