开发者

java FileChannel transferFrom questions?

Following is my method to append one file onto another file.

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

The result is strange to me. When the baseFile is empty, it will copy the new File to that baseFile, but then that baseFile is not empty, it will make that file empty instead of append newFile onto it. Don't know why. Set the outChannel position to baseFileSize or baseFileSize + 1 makes no difference.

If the baseFile is not empty, the baseFileSize is right size but baseFileSize2 is always 0. don't know why.

Anybody can point out what's wrong here? I may missing something. thanks,


I think you need to tell the FileOutputStream to append (default is overwrite):

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜