gpt4 book ai didi

java : corrupted zip file created when copy using nio

转载 作者:行者123 更新时间:2023-12-01 20:24:39 27 4
gpt4 key购买 nike

我已经实现了以下代码来复制文件(二进制文件)代码

private void copyFileWithChannels(File aSourceFile, File aTargetFile) {
log("Copying files with channels.");
FileChannel inChannel = null;
FileChannel outChannel = null;
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(aSourceFile);
inChannel = inStream.getChannel();
outStream = new FileOutputStream(aTargetFile);
outChannel = outStream.getChannel();
long bytesTransferred = 0;
while(bytesTransferred < inChannel.size()){
bytesTransferred += inChannel.transferTo(0, inChannel.size(), outChannel);
}
}
catch(FileNotFoundException e){
log.error("FileNotFoundException in copyFileWithChannels()",e);
}
catch (IOException e) {
log.error("IOException in copyFileWithChannels()",e);
}
catch (Exception e) {
log.error("Exception in copyFileWithChannels()",e);
}
finally {
try{
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
if (inStream != null) inStream.close();
if (outStream != null) outStream.close();
}catch(Exception e){
log.error("Exception in copyFileWithChannels() while closing the stream",e);
}
}

}

我有一个 zip 文件的测试代码。当我验证文件时,我发现生成的文件已损坏(大小增加)。源zip文件大约9GB。

最佳答案

试试这个:

  while(bytesTransferred < inChannel.size()){
bytesTransferred += inChannel.transferTo(bytesTransferred, inChannel.size() - bytesTransferred, outChannel);
}

另外,我会引用 IOUtils 实现,作为引用

https://github.com/apache/commons-io/blob/master/src/main/java/org/apache/commons/io/FileUtils.java

具体来说

private static void doCopyFile(final File srcFile, final File destFile, final boolean preserveFileDate)

关于java : corrupted zip file created when copy using nio,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44068282/

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