2009-10-30 86 views
1

以下是我將一個文件追加到另一個文件的方法。java FileChannel轉移問題?

public static void appendFile(File baseFile, File newFile) throws IOException { 
    long baseFileSize = baseFile.length(); 
    FileChannel outChannel = new FileOutputStream(baseFile).getChannel(); 
    long position1 = outChannel.position(); 
    outChannel.position(baseFileSize); 
    long position2 = outChannel.position(); 
    long baseFileSize2 = baseFile.length(); 
    FileChannel inChannel = new FileInputStream(newFile).getChannel(); 
    System.err.println("appendFile() baseFile=" + baseFile.getAbsolutePath() + 
      ", size=" + baseFileSize + ", size2=" + baseFileSize2 + 
      ", position1=" + position1 + ", position2=" + position2 + 
      ", newFile=" + newFile.getAbsolutePath() + ", size=" + inChannel.size()); 
    try { 
     outChannel.transferFrom(inChannel, baseFileSize, inChannel.size()); 
    } 
    catch (IOException e) { 
     throw e; 
    } 
    finally { 
     if (outChannel != null) outChannel.close(); 
     if (inChannel != null) inChannel.close(); 
    } 
} 

結果對我來說很奇怪。當baseFile爲空時,它會將新文件複製到該baseFile,但該baseFile不爲空,它將使該文件爲空而不是將newFile附加到該文件上。不知道爲什麼。將outChannel位置設置爲baseFileSize或baseFileSize + 1沒有區別。

如果baseFile不是空的,baseFileSize是正確的大小,但baseFileSize2總是0.不知道爲什麼。

有人可以指出這裏有什麼問題嗎?我可能想念一些東西。謝謝,

回答

2

我認爲你需要告訴FileOutputStream追加(默認爲覆蓋):

FileChannel outChannel = new FileOutputStream(baseFile, true).getChannel(); 
+0

如果覆蓋,它不應該讓baseFile空。我會測試它。 – 5YrsLaterDBA 2009-10-30 19:36:51

+0

測試過,你是對的。謝謝。 – 5YrsLaterDBA 2009-10-30 19:39:06