集册 Java实例教程 差异文件

差异文件

欢马劈雪     最近更新时间:2020-01-02 10:19:05

432
差异文件

/*

 * Copyright (c) 2015. Philip DeCamp

 * Released under the BSD 2-Clause License

 * http://opensource.org/licenses/BSD-2-Clause

 */
 /** 
 来 自 
 时代Java - nowjava.com
 **/

//package com.nowjava;

import java.io.*;

import java.nio.ByteBuffer;


public class Main {

    public static boolean diff(File f1, File f2) throws IOException {

        if (f1 != null && !f1.exists())

            f1 = null;


        if (f2 != null && !f2.exists())

            f2 = null;


        if (f1 == f2 || f1 != null && f1.equals(f2))

            return false;
//n o w j a v a . c o m 提 供

        if (f1 == null)

            return f2 != null && f2.length() != 0;


        if (f2 == null)

            return f1 != null && f1.length() != 0;


        long len = f1.length();


        if (len != f2.length())

            return true;


        DataInputStream s1 = new DataInputStream(new BufferedInputStream(

                new FileInputStream(f1)));

        DataInputStream s2 = new DataInputStream(new BufferedInputStream(

                new FileInputStream(f2)));


        long p = 0;


        for (; p < len - 7; p += 8) {

            if (s1.readLong() != s2.readLong())

                return true;

        }


        for (; p < len; p++) {

            if (s1.read() != s2.read())

                return true;

        }


        s1.close();

        s2.close();

        return false;

    }


    public static boolean diff(File f1, ByteBuffer b2) throws IOException {

        if (f1 != null && !f1.exists())

            f1 = null;


        if (b2 != null)

            b2 = b2.slice();


        if (f1 == null)

            return b2 != null && b2.remaining() != 0;


        if (b2 == null)

            return f1 != null && f1.length() != 0;


        if (f1.length() != b2.remaining())

            return true;


        DataInputStream s1 = new DataInputStream(new BufferedInputStream(

                new FileInputStream(f1)));

        final int len = b2.capacity();

        int p = 0;


        for (; p < len - 7; p += 8) {

            if (s1.readLong() != b2.getLong())

                return true;

        }


        for (; p < len; p++) {

            if (s1.read() != (b2.get() & 0xFF))

                return true;

        }


        s1.close();

        return false;

    }


    public static boolean diff(ByteBuffer b1, ByteBuffer b2)

            throws IOException {

        if (b1 == b2 || b1 != null && b1.equals(b2))

            return false;


        if (b1 == null)

            return b2 != null && b2.remaining() != 0;


        
展开阅读全文