以下是我将一个文件追加到另一个文件的方法。
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();