gpt4 book ai didi

java - Java 7 中的 Files.isSameFile

转载 作者:行者123 更新时间:2023-11-30 06:02:50 26 4
gpt4 key购买 nike

我试图通过制作两个相同的文件并稍后使用来进行文件保护Files.isSameFile 检查其中之一是否已被编辑。这是我的代码,不起作用。

                Path path = Paths.get("zapis.lnk");
Path path2 = Paths.get("C:/zapis.lnk");

if (Files.isSameFile(path, path2)){
System.out.println("It is a copy");
} else {
System.out.println("It's not a copy");
}

此刻,我已使用 Windows 资源管理器将 zapis.lnk 复制到 C: 但在我尝试运行我的应用程序后,它显示“这不是副本”。我应该使用什么代码来检查它?

最佳答案

根据定义,两个不同的物理文件不能是同一个文件,即使它们具有完全相同的内容。正如javadoc所述, Files.isSameFile() 测试是否:

two paths locate the same file.

Files.isSameFile() 仅当 Path 引用相同文件时才返回 true,例如:

Path path = Paths.get("C:/folder/zapis.lnk");
Path path2 = Paths.get("C:/folder").resolve("zapis.lnk");
Files.isSameFile(path, path2); // return true

根据您的要求,您需要比较两个文件的字节,为了以优化的方式执行操作,您应该首先比较文件长度,然后再比较它们的字节。
您可以使用强大的第三个库来为您做到这一点。

例如:FileUtils.contentEquals()指定如下:

Compares the contents of two files to determine if they are equal or not. This method checks to see if the two files are different lengths or if they point to the same file, before resorting to byte-by-byte comparison of the contents.

所以你可以这样做:

boolean isContentEqual = FileUtils.contentEquals(path.toFile(), path2.toFile());

关于java - Java 7 中的 Files.isSameFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51921440/

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