java FileChannel transferFrom问题?

时间:2009-10-30 19:25:11

标签: java

以下是我将一个文件附加到另一个文件的方法。

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.不知道原因。

任何人都可以指出这里有什么问题?我可能会遗漏一些东西感谢,

1 个答案:

答案 0 :(得分:2)

我认为你需要告诉FileOutputStream追加(默认是覆盖):

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