Java uses IO stream to compare the contents of two files to determine whether they are the same file

Compare the contents of two files for the same

public class CompareFiles {
    
    
    public static void main(String[] args) {
    
    
        //比较的是项目下的两个文件,所以没有加路径。
        System.out.println(isSameFile(new File("xue.html"), new File("xue_ok1.html")));
    }
    //创建一个方法,两个参数为所比较的文件,返回值是boolean类型
    public static boolean isSameFile(File src, File dst) {
    
    
        boolean flag = false;//默认为flase
        //首先先比较两个文件的字节长度,如果相同则继续往下比,如果不同则返回flag;
        if (src.length() == dst.length()) {
    
    
            //运用FileInputStream进行入去文件
            try (var aa = new FileInputStream(src); var bb = new FileInputStream(dst)) {
    
    
                int i = 0;//定义一个i,aa.read()与bb.read()从第一个字节判断
                while (aa.read() == bb.read()) {
    
    
                    ++i;
                    //如果比较的文件字节较大,可以跳着读取,读取前100个字节进行比较,然后在读取最后100个字节进行比较。
                    if (i >= 100) {
    
    
                        aa.skip(src.length() - 100);
                        bb.skip(dst.length() - 100);
                    }
                    //如果读取的字节相等,且最后都==-1,证明已经读完且两个文件是同一个文件,返回true;
                    if (aa.read() == -1 || bb.read() == -1) {
    
    
                        flag = true;
                        break;
                    }
                }
            } catch (Exception e) {
    
    
                System.out.println(e);
            }
        }
        return flag;
    }

Guess you like

Origin blog.csdn.net/qq_59088934/article/details/128569695