最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java如何比較兩個任意文件是否相同

 更新時間:2024年04月20日 16:43:59   作者:JFS_Study  
這篇文章主要為大家詳細(xì)介紹了Java如何實(shí)現(xiàn)比較兩個任意文件是否相同,文中的示例代碼簡潔易懂,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

一、比較規(guī)則

  • 先比較兩個文件的長度,如果不一樣則文件肯定不一樣。
  • 否則將文件讀取出來,一個字節(jié)一個字節(jié)的比較二者內(nèi)容是否相同。
public class FileCompare {
    public static void main(String[] args) {
        System.out.println("請依次輸入兩個文件的全路徑和文件名:");
        System.out.println("firstFile:");
        String firstFile = inputFileName();
        System.out.println("secondFile:");
        String secondFile = inputFileName();
        System.out.println("Start to compare ...");
        FileCompare fileCompare = new FileCompare();
        fileCompare.compareFile(firstFile, secondFile);
    }

    private static String inputFileName() {
        BufferedReader buffRead = new BufferedReader(new InputStreamReader(System.in));
        String fileName = null;
        try {
            fileName = buffRead.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    private void compareFile(String firFile, String secFile) {
        try {
            BufferedInputStream fir = new BufferedInputStream(new FileInputStream(firFile));
            BufferedInputStream sec = new BufferedInputStream(new FileInputStream(secFile));
            //比較文件的長度是否一樣
            if (fir.available() == sec.available()) {
                while (true) {
                    int firRead = fir.read();
                    int secRead = sec.read();
                    if (firRead == -1 || secRead == -1) {
                        System.out.println("two files are same!");
                        break;
                    } else if (firRead != secRead) {
                        System.out.println("Files not same!");
                        break;
                    }
                }
            } else {
                System.out.println("two files are different!");
            }
            fir.close();
            sec.close();
            return;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

二、File 中的 length() 與IO中 InputStream 類中的 available()

1??File 中的 length() 返回 long,表示文件的大小。

2??IO 中 InputStream 類中的 available() 返回 int。表示該 inputstream 在不被阻塞的情況下一次可以讀取到的數(shù)據(jù)長度。

三、方法補(bǔ)充

除了上文的方法,小編還為大家整理了其他Java比較文件的方法,希望對大家有所幫助

java實(shí)現(xiàn)兩個文件對比

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class check {
    public static void main(String[] args) {
        Set<String> allStuNames = new HashSet<>();

        try {
            FileReader fileReader = new FileReader("name.txt");
            BufferedReader bufferedReader = new BufferedReader(fileReader);

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                // 逐行處理文本內(nèi)容
//                System.out.println(line);
                allStuNames.add(line);
            }

            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

//        System.out.println(allStuNames);

        List<String> lst = new ArrayList<>();

        try {
            FileReader fileReader = new FileReader("a.txt");
            BufferedReader bufferedReader = new BufferedReader(fileReader);

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                // 逐行處理文本內(nèi)容
//                System.out.println(line);
                lst.add(line);
            }

            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        for(String desc : lst){
            for(String name : allStuNames){
                if(desc.contains(name)){
                    System.out.println(name);
                    System.out.println(desc);
                }
            }
        }
    }
}

利用md5判斷兩個文件是否相同

例子:

根據(jù)不同路徑下兩個文件來判斷:

package com.letv.test;
 
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
 
public class CheckSameFile {
	public static char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7',
			'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
 
	public static void main(String[] args) {
		String path1 = "d:/test/abc.jpg";
		String path2 = "d:/test/asd/abc.jpg";
 
		String hash_path1 = null;
		String hash_path2 = null;
		try {
			hash_path1 = getHash(path1, "MD5");
			hash_path2 = getHash(path2, "MD5");
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("path1 md5:" + hash_path1);
		System.out.println("path2 md5:" + hash_path2);
		if (hash_path1.endsWith(hash_path2)) {
			System.out.println("文件相同");
		} else {
			System.out.println("文件不相同");
		}
	}
 
	/**
	 * 獲得文件md5值
	 */
	public static String getHash(String fileName, String hashType)
			throws Exception {
		InputStream fis;
		fis = new FileInputStream(fileName);
		byte[] buffer = new byte[1024];
		MessageDigest md5 = MessageDigest.getInstance(hashType);
		int numRead = 0;
		while ((numRead = fis.read(buffer)) > 0) {
			md5.update(buffer, 0, numRead);
		}
		fis.close();
		return toHexString(md5.digest());
	}
 
	/**
	 * md5轉(zhuǎn)成字符串
	 */
	public static String toHexString(byte[] b) {
		StringBuilder sb = new StringBuilder(b.length * 2);
		for (int i = 0; i < b.length; i++) {
			sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
			sb.append(hexChar[b[i] & 0x0f]);
		}
		return sb.toString();
	}
}

通過比較文件每一個字節(jié)判斷

	public static boolean isSameFile(String filePath1, String filePath2) {
        FileInputStream fis1 = null;
        FileInputStream fis2 = null;

        try {
            fis1 = new FileInputStream(filePath1);
            fis2 = new FileInputStream(filePath2);

            // 獲取文件的總字節(jié)數(shù)
            int len1 = fis1.available();
            int len2 = fis2.available();

            // 判斷兩個文件的字節(jié)長度是否一樣,長度相同則比較具體內(nèi)容
            if (len1 == len2) {
                // 建立字節(jié)緩沖區(qū)
                byte[] data1 = new byte[len1];
                byte[] data2 = new byte[len2];

                // 將文件寫入緩沖區(qū)
                fis1.read(data1);
                fis2.read(data2);

                // 依次比較文件中的每個字節(jié)
                for (int i = 0; i < len1; i++) {
                    if (data1[i] != data2[i]) {
                        System.out.println("文件內(nèi)容不一樣");
                        return false;
                    }
                }
                System.out.println("文件內(nèi)容相同");
                return true;
            } else {
                // 文件長度不一樣,內(nèi)容肯定不同
                System.out.println("文件內(nèi)容不同");
                return false;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 關(guān)閉資源
            if (fis1!=null){
                try {
                    fis1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis2!=null){
                try {
                    fis2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

使用緩沖流比較,在比較大文件時效率相比普通流效率高

    public static boolean isSameFile2(String filePath1, String filePath2) {
        BufferedInputStream bis1 = null;
        BufferedInputStream bis2 = null;
        FileInputStream fis1 = null;
        FileInputStream fis2 = null;

        try {
            // 獲取文件輸入流
            fis1 = new FileInputStream(filePath1);
            fis2 = new FileInputStream(filePath2);
            // 將文件輸入流包裝成緩沖流
            bis1 = new BufferedInputStream(fis1);
            bis2 = new BufferedInputStream(fis2);

            // 獲取文件字節(jié)總數(shù)
            int len1 = bis1.available();
            int len2 = bis2.available();

            // 判斷兩個文件的字節(jié)長度是否一樣,長度相同則比較具體內(nèi)容
            if (len1 == len2) {
                // 建立字節(jié)緩沖區(qū)
                byte[] data1 = new byte[len1];
                byte[] data2 = new byte[len2];

                // 將文件寫入緩沖區(qū)
                bis1.read(data1);
                bis2.read(data2);
                // 依次比較文件中的每個字節(jié)
                for (int i = 0; i < len1; i++) {
                    if (data1[i] != data2[i]) {
                        System.out.println("文件內(nèi)容不一致");
                        return false;
                    }
                }
                System.out.println("文件內(nèi)容一致");
                return true;
            } else {
                System.out.println("文件長度不一致,內(nèi)容不一致");
                return false;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis1 != null) {
                try {
                    bis1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis2 != null) {
                try {
                    bis2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis1 != null) {
                try {
                    fis1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis2 != null) {
                try {
                    fis2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return false;
    }

將文件分多次讀入,然后通過MessageDigest進(jìn)行MD5加密,最后再通過BigInteger類提供的方法進(jìn)行16進(jìn)制的轉(zhuǎn)換

	/**
     * 計算文件的MD5值
     *
     * @param file
     * @return
     */
    public static String getFileMD5(File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte[] buffer = new byte[8192];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer)) != -1) {
                digest.update(buffer, 0, len);
            }
            BigInteger bigInt = new BigInteger(1, digest.digest());
            return bigInt.toString(16);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

public static void main(String[] args) throws IOException {

        String filePath1="/Users/zhouzhxu/desktop/test.csv";
        String filePath2="/Users/zhouzhxu/desktop/test2.csv";

        String fileMD51 = getFileMD5(new File(filePath1));
        String fileMD52 = getFileMD5(new File(filePath2));

        System.out.println(fileMD51);
        System.out.println(fileMD52);

    }

到此這篇關(guān)于Java如何比較兩個任意文件是否相同的文章就介紹到這了,更多相關(guān)Java比較文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • java實(shí)現(xiàn)的滿天星效果實(shí)例

    java實(shí)現(xiàn)的滿天星效果實(shí)例

    這篇文章主要介紹了java實(shí)現(xiàn)滿天星效果的方法,涉及Java繪圖的應(yīng)用,非常具有實(shí)用價值,需要的朋友可以參考下
    2014-11-11
  • 淺談java的接口和C++虛類的相同和不同之處

    淺談java的接口和C++虛類的相同和不同之處

    下面小編就為大家?guī)硪黄獪\談java的接口和C++虛類的相同和不同之處。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧,祝大家游戲愉快哦
    2016-12-12
  • 在SSM中配置了事務(wù)控制但沒生效的問題

    在SSM中配置了事務(wù)控制但沒生效的問題

    這篇文章主要介紹了在SSM中配置了事務(wù)控制但沒生效的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • JavaWeb項目中DLL文件動態(tài)加載方法

    JavaWeb項目中DLL文件動態(tài)加載方法

    在JavaWeb項目中,有時候我們需要在運(yùn)行時動態(tài)加載DLL文件(在Windows中是DLL,在Linux中是SO文件),這通常用于實(shí)現(xiàn)一些特定的功能,比如調(diào)用本機(jī)代碼或者使用某些特定于操作系統(tǒng)的API,本文將介紹如何在JavaWeb項目中動態(tài)加載DLL文件,需要的朋友可以參考下
    2024-12-12
  • java中char類型轉(zhuǎn)換成int類型的2種方法

    java中char類型轉(zhuǎn)換成int類型的2種方法

    這篇文章主要給大家介紹了關(guān)于java中char類型轉(zhuǎn)換成int類型的2種方法,因?yàn)閖ava是一門強(qiáng)類型語言,所以在數(shù)據(jù)運(yùn)算中會存在類型轉(zhuǎn)換,需要的朋友可以參考下
    2023-07-07
  • 8個簡單部分開啟Java語言學(xué)習(xí)之路 附j(luò)ava學(xué)習(xí)書單

    8個簡單部分開啟Java語言學(xué)習(xí)之路 附j(luò)ava學(xué)習(xí)書單

    8個簡單部分開啟Java語言學(xué)習(xí)之路,附j(luò)ava學(xué)習(xí)書單,這篇文章主要向大家介紹了學(xué)習(xí)java語言的方向,感興趣的小伙伴們可以參考一下
    2016-09-09
  • Mybatis省略@Param注解原理分析

    Mybatis省略@Param注解原理分析

    這篇文章主要介紹了Mybatis省略@Param注解原理分析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-06-06
  • MyBatis中criteria的or(或查詢)語法說明

    MyBatis中criteria的or(或查詢)語法說明

    這篇文章主要介紹了MyBatis中criteria的or(或查詢)語法說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • Eclipse中使用Maven創(chuàng)建Java Web工程的實(shí)現(xiàn)方式

    Eclipse中使用Maven創(chuàng)建Java Web工程的實(shí)現(xiàn)方式

    這篇文章主要介紹了Eclipse中使用Maven創(chuàng)建Java Web工程的實(shí)現(xiàn)方式的相關(guān)資料,希望通過本文能幫助到大家,讓大家實(shí)現(xiàn)這樣的方式,需要的朋友可以參考下
    2017-10-10
  • Java基礎(chǔ)鞏固系列包裝類代碼實(shí)例

    Java基礎(chǔ)鞏固系列包裝類代碼實(shí)例

    這篇文章主要介紹了Java包裝類,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04

最新評論

巴林右旗| 牙克石市| 会东县| 安多县| 寿宁县| 万宁市| 贞丰县| 嘉义县| 大兴区| 奇台县| 彭泽县| 华安县| 延津县| 乐亭县| 邵武市| 天水市| 宜兰县| 清涧县| 九龙坡区| 吴忠市| 静宁县| 天门市| 保德县| 乌拉特中旗| 鹤岗市| 石屏县| 仲巴县| 保康县| 佛学| 宁远县| 昌江| 赤水市| 宣化县| 沂源县| 金秀| 吴江市| 靖边县| 南皮县| 大丰市| 孟州市| 新兴县|