在创建包含某些内容的文件后,我需要创建一个MD5文件。
但是我发现一个问题,文件的md5值与实际的文件值不同,尽管我没有改变文件本身。
最后,我发现如果我在try-with-resources块中创建md5文件,md5会发生变化。我写了下面的代码片段来验证我的猜测
public static void main(String[] args) throws IOException {
String filePath = "D:\\push\\file\\imei2device\\imei2device.txt";
File f = new File(filePath);
try (FileWriter fw = new FileWriter(f);){
fw.write("something");
//createMD5File(filePath);// create here, NOT OK!
}
catch (Exception ex) {
ex.printStackTrace();
}
createMD5File(filePath);// create here, ok
logger.info("create md5 file successfully, notModified: {}", MappedFileReader.isFileNotModified(filePath));
}当我把createMD5File放在两个不同的地方时,我会发现一个MD5的值是不同的。
我怀疑当FileWriter关闭时,文件本身是不同的,就像EOF?
发布于 2017-09-27 10:05:45
不是的。磁盘上没有显式的EOF,您需要等待文件完成写入,然后再尝试使用文件内容计算MD5 (即在计算flush()之前先计算文件)。或者,根据您从内存中写入的内容计算散列(这将比从磁盘重新读取数据更快)。
https://stackoverflow.com/questions/46438350
复制相似问题