验证文件是否已在 Java 中复制
我正在努力将一些文件移动到项目中的不同目录,并且效果很好,除了我无法验证它是否已正确移动这一事实。
我想验证副本的长度与原始文件的长度相同,然后我想删除原始文件。我在进行验证之前关闭了两个 FileStream,但由于大小不同,它仍然失败。下面是我用于关闭流、验证和删除的代码。
in.close();
out.close();
if (encCopyFile.exists() && encCopyFile.length() == encryptedFile.length())
encryptedFile.delete();
在此之前的其余代码是使用 Util 来复制流,并且一切正常,所以我实际上只需要一个更好的验证方法。
I'm working on moving some files to a different directory in my project and it's working great, except for the fact that I can't verify it's moved properly.
I want to verify the length of the copy is the same as the original and then I want to delete the original. I'm closing both FileStreams before I do my verification but it still fails because the sizes are different. Below is my code for closing the streams, verification and deletion.
in.close();
out.close();
if (encCopyFile.exists() && encCopyFile.length() == encryptedFile.length())
encryptedFile.delete();
The rest of the code before this is using a Util to copy the streams, and it's all working fine so really I just need a better verification method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
一种很好的检查方法是比较 md5 哈希值。检查文件长度并不意味着它们是相同的。虽然 md5 哈希值也不意味着它们相同,但它比检查长度要好,尽管过程较长。
One wonderful way you can check is to compare md5 hashes. Checking file length doesn't mean they are the same. While md5 hashes doesn't mean they are the same either, it is better than checking the length albeit a longer process.
您可以在复制操作中包含校验和。对目标文件执行校验和,并查看它是否与源文件上的校验和匹配。
You could include a checksum in your copy operation. Perform a checksum on the destination file and see that it matches a checksum on the source.
您可以使用 commons io:
或者可以使用校验和方法:
You could use commons io:
or you could use checksum methods:
如果复制流时没有出现异常,则应该没问题。确保不要忽略 close 方法抛出的异常!
更新:如果您使用
FileOutputStream
,您还可以在关闭之前通过调用fileOutputStream.getFD().sync()
来确保所有内容都已正确写入你的fileOutputStream
。当然,如果您想绝对确保文件相同,您可以比较它们的校验和/摘要,但这对我来说听起来有点偏执。
If you get no exception while copying streams, you should be OK. Make sure you don't ignore exceptions thrown by close method!
Update: If you use
FileOutputStream
, you can also make sure everything was written properly by callingfileOutputStream.getFD().sync()
before closing yourfileOutputStream
.Of course, if you want to absolutely make sure that files are the same, you can compare their checksums/digests, but that sounds bit paranoid to me.
如果大小不同,则可能您在关闭输出流之前没有刷新输出流。
哪个文件更大?每个文件的大小是多少?您是否真的查看过这两个文件以了解有什么不同?
If the sizes are different, perhaps you are not flushing the output stream before closing it.
Which file is bigger? What are the sizes of each file? Have you actually looked at the two files to see what is different?