gpt4 book ai didi

java FileChannel TransferFrom问题?

转载 作者:行者123 更新时间:2023-11-30 05:15:18 34 4
gpt4 key购买 nike

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

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。不知道为什么。

有人可以指出这里出了什么问题吗?我可能会错过一些东西。谢谢,

最佳答案

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

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

关于java FileChannel TransferFrom问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1651832/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com