2013-11-21 11 views
6

File a.txt assomiglia:Come utilizzare FileChannel per aggiungere il contenuto di un file alla fine di un altro file?

ABC 

File d.txt assomiglia:

DEF 

che sto cercando di prendere "DEF" e aggiungerlo alla "ABC" in modo a.txt sembra

ABC 
DEF 

I metodi che ho provato sempre sovrascrivere completamente la prima voce in modo finisco sempre con:

DEF 

Qui ci sono i due metodi che ho provato:

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

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

... e ho provato

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

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

L'API non è chiara circa le transferTo e transferFrom param descrizioni qui :

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

Grazie per qualsiasi idea.

risposta

3

spostare la posizione del canale di destinazione fino alla fine:

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

Questo è vecchio ma questa impostazione si verifica a causa della modalità che si apre il flusso di output del file. Per chiunque che ha bisogno di questo, provare a

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

Questa dovrebbe essere la risposta accettata! –

1

soluzione nio puro

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

Tuttavia, ho ancora una domanda: perché transferFrom non funziona qui?

Problemi correlati