下面是我将一个文件附加到另一个文件的方法。
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。不知道为什么。
有人能指出这里出了什么问题吗?我可能漏掉了什么。谢谢,
发布于 2009-10-31 03:28:18
我认为你需要告诉FileOutputStream追加(默认是覆盖):
FileChannel outChannel = new FileOutputStream(baseFile, true).getChannel();https://stackoverflow.com/questions/1651832
复制相似问题