Java 比较两个任意文件是否相同

一、比较规则

  1. 先比较两个文件的长度,如果不一样则文件肯定不一样。
  2. 否则将文件读取出来,一个字节一个字节的比较二者内容是否相同。
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 在不被阻塞的情况下一次可以读取到的数据长度。

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JFS_Study

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值