java 判断两个文件是否相同

使用java 如何判断两个文件是否相同呢?

我的做法是

(1)先比较两个文件内容的长度;

(2)在长度相同的情况下,再比较两个文件的MD5值。

【create md5】按钮用于记录source file的文件内容长度和MD5值。

运行主类:CheckSameApp

package com.hw.main;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import com.common.util.SystemUtil;
import com.swing.dialog.DialogUtil;
import com.swing.messagebox.GUIUtil23;

public class CheckSameApp extends JFrame
{
        private static final long serialVersionUID = 1644076682819874235L;
        private JTextField                sourceFileTF;
        private JButton                     browserSourceBtn;
        private JTextField                targetFileTF;
        private JButton                     createmd5Button    = null;
        private JButton                     checkmd5Btn            = null;
        private JButton                     browserTargetBtn = null;
        /***
         * MD5 of last file
         */
        private String                        result                     = null;
        private long                            size_of_file         = 0;
        private JButton                     compareBtn             = null;
        private File                            srcfile                    = null;
        private File                            targfile                 = null;
        protected static String     MESG_DIFF                = "[failed:] they are different";
        protected static String     MESG_SAME                = "[successfully:] they are same completely";

public static void main(String[] args)
        {
                CheckSameApp app = new CheckSameApp();
                app.launchFrame();
        }

public void launchFrame()
        {
                this.setTitle("Compare two files by MD5");
                Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
                this.setSize(700, 200);
                Dimension framesize = this.getSize();
                int x = (int) screensize.getWidth() / 2 - (int) framesize.getWidth()
                        / 2;
                int y = (int) screensize.getHeight() / 2 - (int) framesize.getHeight()
                        / 2;
                this.setLocation(x, y);
                Container c = this.getContentPane();
                layout(c);
                this.setVisible(true);
                this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }

/***
         * setting menu
         */

public void layout(Container c)
        {
                //                setMenu2();
                JPanel mainPane = new JPanel();
                GridBagLayout gridBagLayout = new GridBagLayout();
                gridBagLayout.columnWidths = new int[]
                { 20, 80/*between source file and text field*/, 300, 60, 0 };
                gridBagLayout.rowHeights = new int[]
                { 17, 0, 0, 0, 0, 0, 0, 0, 0, 25, 0, 0 };
                gridBagLayout.columnWeights = new double[]
                { 0.0, 0.0, 1.0, 1.0, Double.MIN_VALUE };
                gridBagLayout.rowWeights = new double[]
                { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0,
                        Double.MIN_VALUE };

mainPane.setLayout(gridBagLayout);
                JLabel ftpServerLb = new JLabel("source file");
                GridBagConstraints gbc_setConnectionsLabel = new GridBagConstraints();
                gbc_setConnectionsLabel.anchor = GridBagConstraints.WEST;
                gbc_setConnectionsLabel.insets = new Insets(0, 0, 5, 5);
                gbc_setConnectionsLabel.gridx = 1;
                gbc_setConnectionsLabel.gridy = 1;
                mainPane.add(ftpServerLb, gbc_setConnectionsLabel);
                //                dialog.add(ftpserverTF);

sourceFileTF = new JTextField();
                if (!SystemUtil.isWindows)
                {
                        sourceFileTF.setText("/home/whuang2/bin/ab.txt");
                }
                else
                {
                        sourceFileTF.setText("");
                }
                GridBagConstraints gbc_connectionsTF = new GridBagConstraints();
                gbc_connectionsTF.fill = GridBagConstraints.HORIZONTAL;
                gbc_connectionsTF.insets = new Insets(0, 0, 5, 5);
                gbc_connectionsTF.gridx = 2;
                gbc_connectionsTF.gridy = 1;
                mainPane.add(sourceFileTF, gbc_connectionsTF);

browserSourceBtn = new JButton("browser source");
                GridBagConstraints gbc_browserSourceBtn = new GridBagConstraints();
                gbc_browserSourceBtn.fill = GridBagConstraints.EAST;
                gbc_browserSourceBtn.insets = new Insets(0, 0, 5, 5);
                gbc_browserSourceBtn.gridx = 3;
                gbc_browserSourceBtn.gridy = 1;
                mainPane.add(browserSourceBtn, gbc_browserSourceBtn);
                browserSourceBtn.addActionListener(new ActionListener()
                {
                        @Override
                        public void actionPerformed(ActionEvent e)
                        {
                                //                                System.out.println("source");
                                boolean isSuccess = DialogUtil.browser3(sourceFileTF,
                                        JFileChooser.FILES_ONLY, CheckSameApp.this);
                                //                                if (isSuccess)
                                //                                {
                                //                                        targetFileTF.setText(SystemUtil.getParentDir(sourceFileTF
                                //                                                        .getText()));
                                //                                }
                        }
                });

JPanel buttonPane = new JPanel();
                //                buttonPane.setColor.red);< /font>
                GridBagConstraints gbc_buttonPane = new GridBagConstraints();
                gbc_buttonPane.fill = GridBagConstraints.HORIZONTAL;
                gbc_buttonPane.insets = new Insets(0, 0, 5, 5);
                gbc_buttonPane.gridx = 2;
                gbc_buttonPane.gridy = 2;
                mainPane.add(buttonPane, gbc_buttonPane);

createmd5Button = new JButton("create md5");
                checkmd5Btn = new JButton("check");
                checkmd5Btn.setEnabled(false);
                buttonPane.add(createmd5Button);
                buttonPane.add(checkmd5Btn);
                createmd5Button.addActionListener(new ActionListener()
                {
                        @Override
                        public void actionPerformed(ActionEvent e)
                        {
                                if (!validate3(true))
                                {
                                        return;
                                }
                                sourceFileTF.setEditable(false);
                                new Thread(new Runnable()
                                {
                                        @Override
                                        public void run()
                                        {
                                                createmd5Button.setEnabled(false);
                                                size_of_file = srcfile.length();
                                                result = SystemUtil.getFileMD5(srcfile);
                                                checkmd5Btn.setEnabled(true);
                                                createmd5Button.setEnabled(true);
                                        }
                                }).start();

}
                });

checkmd5Btn.addActionListener(new ActionListener()
                {
                        @Override
                        public void actionPerformed(ActionEvent e)
                        {
                                //                                if (!validate3(true))
                                //                                {
                                //                                        return;
                                //                                }
                                long size_of_file2 = srcfile.length();
                                if (size_of_file2 != size_of_file)
                                {
                                        System.out.println("by size");
                                        GUIUtil23.errorDialog(MESG_DIFF);
                                        return;
                                }

new Thread(new Runnable()
                                {
                                        @Override
                                        public void run()
                                        {
                                                checkmd5Btn.setEnabled(false);
                                                String result2;
                                                sourceFileTF.setEditable(true);
                                                result2 = SystemUtil.getFileMD5(srcfile);
                                                boolean isSame2=isSame(result2, result);
                                                checkmd5Btn.setEnabled(true);
                                                if (isSame2)
                                                {
                                                        GUIUtil23.infoDialog(MESG_SAME);
                                                }
                                                else
                                                {
                                                        GUIUtil23.errorDialog(MESG_DIFF);
                                                }
                                        }
                                }).start();
                                
                        }
                });

JLabel targetLabel = new JLabel("target file");
                GridBagConstraints gbc_driveClassLabel = new GridBagConstraints();
                gbc_driveClassLabel.anchor = GridBagConstraints.WEST;
                gbc_driveClassLabel.insets = new Insets(0, 0, 5, 5);
                gbc_driveClassLabel.gridx = 1;
                gbc_driveClassLabel.gridy = 3;
                mainPane.add(targetLabel, gbc_driveClassLabel);

targetFileTF = new JTextField();
                if (!SystemUtil.isWindows)
                {
                        targetFileTF.setText("/home/whuang2/bin/wh_dos2unix");
                }
                GridBagConstraints gbc_driveClassTF = new GridBagConstraints();
                gbc_driveClassTF.insets = new Insets(0, 0, 5, 5);
                gbc_driveClassTF.fill = GridBagConstraints.HORIZONTAL;
                gbc_driveClassTF.gridx = 2;
                gbc_driveClassTF.gridy = 3;
                mainPane.add(targetFileTF, gbc_driveClassTF);
                targetFileTF.setColumns(10);

browserTargetBtn = new JButton("browser target");
                GridBagConstraints gbc_browserTargetBtn = new GridBagConstraints();
                gbc_browserTargetBtn.fill = GridBagConstraints.EAST;
                gbc_browserTargetBtn.insets = new Insets(0, 0, 5, 5);
                gbc_browserTargetBtn.gridx = 3;
                gbc_browserTargetBtn.gridy = 3;
                mainPane.add(browserTargetBtn, gbc_browserTargetBtn);
                browserTargetBtn.addActionListener(new ActionListener()
                {
                        @Override
                        public void actionPerformed(ActionEvent e)
                        {
                                //                                System.out.println("target");
                                DialogUtil.browser3(targetFileTF,
                                        JFileChooser.FILES_AND_DIRECTORIES, CheckSameApp.this);
                        }
                });
                compareBtn = new JButton("compare");
                GridBagConstraints gbc_runBtn = new GridBagConstraints();
                gbc_runBtn.fill = GridBagConstraints.EAST;
                gbc_runBtn.insets = new Insets(0, 0, 5, 5);
                gbc_runBtn.gridx = 4;
                gbc_runBtn.gridy = 3;
                mainPane.add(compareBtn, gbc_runBtn);

compareBtn.addActionListener(new ActionListener()
                {

@Override
                        public void actionPerformed(ActionEvent e)
                        {
                                if (!validate3(false))
                                {
                                        return;
                                }

long size_of_targfile = targfile.length();
                                long size_of_srcfile = srcfile.length();
                                if (size_of_targfile != size_of_srcfile)
                                {
                                        System.out.println("by size");
                                        GUIUtil23.errorDialog(MESG_DIFF);
                                        return;
                                }
                                new Thread(new Runnable()
                                {
                                        @Override
                                        public void run()
                                        {
                                                compareBtn.setEnabled(false);
                                                String result_source = SystemUtil.getFileMD5(srcfile);
                                                String result_target;
                                                result_target = SystemUtil.getFileMD5(targfile);
                                                boolean isSame2=isSame(result_source, result_target);
                                                compareBtn.setEnabled(true);
                                                if (isSame2)
                                                {
                                                        GUIUtil23.infoDialog(MESG_SAME);
                                                }
                                                else
                                                {
                                                        GUIUtil23.errorDialog(MESG_DIFF);
                                                }

}
                                }).start();
                        }
                });

c.add(mainPane, BorderLayout.CENTER);
                //                System.out.println(c.getLayout());
                //new JScrollPane(text)
        }

//        private String create_md5(String filePath)
        //        {
        //                try
        //                {
        //                        return create_md5(filePath, null);
        //                }
        //                catch (IOException e)
        //                {
        //                        e.printStackTrace();
        //                }
        //                return null;
        //        }

/***
         *
         * @param result_source : such as b79898bb7907648871745cd5422c79ce     /home/whuang2/bin/ab.txt
         * @param result_target
         * @return
         */
        private boolean isSame(String result_source, String result_target)
        {
                if (result_source == null || result_target == null)
                {
                        return false;
                }
                return (result_source.split("[ \t]")[0].equals(result_target
                                .split("[ \t]")[0]));
        }

//        private String create_md5(String filePath, JButton button)
        //                        throws IOException
        //        {
        //                //                String sourceFile=sourceFileTF.getText();
        //                //
        //                if (!new File(filePath).exists())
        //                {
        //                        System.out.println("does not exist");
        //                        return null;
        //                }
        //                String result2 = null;
        //                String[] commands = null;
        //                if (SystemUtil.isWindows)
        //                {
        //                        String md5deepPath = null;
        //                        if (SystemUtil.isOS32bit)
        //                        {
        //                                md5deepPath = "win32\\md5deep.exe";
        //                        }
        //                        else
        //                        {
        //                                md5deepPath = "win64\\md5deep64.exe";
        //                        }
        //
        //                        commands = new String[]
        //                        { System.getProperty("user.dir") + "\\md5deep\\" + md5deepPath,
        //                                "-b", filePath };
        //                }
        //                else
        //                {
        //                        commands = new String[]
        //                        { "md5sum", filePath };
        //                }
        //                ProcessBuilder pb = new ProcessBuilder(commands);
        //                //                if (directory != null)
        //                //                {
        //                //                        pb.directory(directory);
        //                //                }
        //                //                Map<String, String> env = pb.environment();
        //                //                env.put("$HOME", "/home/whuang2");
        //                MyProcess proc = null;
        //                try
        //                {
        //                        proc = new MyProcess(pb.start());
        //                        final CheckSameSwingWorker worker = new CheckSameSwingWorker(proc);
        //                        worker.execute();
        //
        //                        proc.waitFor();
        //                        if (button != null)
        //                        {
        //                                button.setEnabled(true);
        //                        }
        //                        result2 = worker.getStringbuf().toString();
        //                        //                        System.out.println("before exitValue");
        //                        //                        System.out.println("exit code:" + proc.exitValue());
        //                        //                        System.out.println("result:" + result);
        //                        //                        System.out.println("after exitValue");
        //                        //                        return result2;
        //                }
        //                catch (InterruptedException e1)
        //                {
        //                        e1.printStackTrace();
        //                }
        //                catch (IOException e2)
        //                {
        //                        e2.printStackTrace();
        //                }
        //                return result2;
        //        }

private boolean validate3(boolean isSelf)
        {
                String sourceFile = sourceFileTF.getText();
                String targetFile_dir = targetFileTF.getText();
                if (sourceFile == null || sourceFile.equals(""))
                {
                        GUIUtil23
                                        .warningDialog("source file can not be empty,please select again    !");
                        sourceFileTF.requestFocus();//focus

return false;
                }
                if (!isSelf)
                {
                        if (targetFile_dir == null || targetFile_dir.equals(""))
                        {
                                GUIUtil23
                                                .warningDialog("target file can not be empty,please select again !");
                                targetFileTF.requestFocus();//focus
                                return false;
                        }
                }
                //                                System.out.println("source file:" + sourceFile);
                //                                System.out.println("target file:" + targetFile_dir);
                srcfile = new File(sourceFile);
                if (!srcfile.exists())
                {
                        GUIUtil23
                                        .warningDialog("source file does not exist,please select again!");
                        sourceFileTF.requestFocus();//focus
                        sourceFileTF.selectAll();
                        return false;
                }
                if (srcfile.exists() && srcfile.isDirectory())
                {
                        GUIUtil23
                                        .warningDialog("source file can not be directory,please select again!");
                        sourceFileTF.requestFocus();//focus
                        sourceFileTF.selectAll();
                        return false;
                }
                if (!isSelf)
                {
                        {
                                targfile = new File(targetFile_dir);
                                if (!targfile.exists())
                                {
                                        GUIUtil23
                                                        .warningDialog("target file does not exist,please select again!");
                                        targetFileTF.requestFocus();//focus
                                        targetFileTF.selectAll();
                                        return false;
                                }
                                if (targfile.exists() && targfile.isDirectory())
                                {
                                        GUIUtil23
                                                        .warningDialog("target file can not be directory,please select again!");
                                        targetFileTF.requestFocus();//focus
                                        targetFileTF.selectAll();
                                        return false;
                                }
                        }
                }
                return true;

}

//        public static void main2(String[] args)
        //        {
        //                String sourceFile = "/home/whuag2/workspace/io0007-find_progess/src/com/cmd/dos/hw/util/CMDUtil.java";
        //                md5(sourceFile);
        //        }

}

swingwork类:CheckSameSwingWorker

package com.hw.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import javax.swing.SwingWorker;

import com.common.util.MyProcess;

public class CheckSameSwingWorker extends SwingWorker<Boolean, Character>
{
        private BufferedReader br_right             = null;
        private BufferedReader br_error             = null;
        private MyProcess            myprocess            = null;
        private char                     word                     = ‘ ‘;
        private int                        tmp                        = 0;
        private boolean                isPrintVerbose = false;
        private StringBuffer     stringbuf            = new StringBuffer();

public CheckSameSwingWorker(MyProcess myprocess, BufferedReader br)
        {
                this.br_right = br;
                this.myprocess = myprocess;

}

public CheckSameSwingWorker(MyProcess myprocess)
        {
                this.myprocess = myprocess;
                br_right = new BufferedReader(new InputStreamReader(
                        myprocess.getInputStream()), 4096);
                br_error = new BufferedReader(new InputStreamReader(
                        myprocess.getErrorStream()), 4096);
        }

@Override
        protected Boolean doInBackground() throws Exception
        {
                while ((tmp = br_right.read()) != -1)
                {
                        word = (char) tmp;
                        publish(word);
                }
                while ((tmp = br_error.read()) != -1)
                {
                        word = (char) tmp;
                        publish(word);
                }
                if (isPrintVerbose)
                {
                        System.out.println("doInBackground() over");
                }
                return true;
        }

@Override
        protected void process(List<Character> chunks)
        {
                for (char temp : chunks)
                {
                        {
//                                System.out.print(temp);
                                this.stringbuf.append(temp);
                        }
                }
        }

public StringBuffer getStringbuf()
        {
                return stringbuf;
        }

/***
         * main thread can‘t execute next command(below waitFor())
         * until done() is executed
         */
        @Override
        protected void done()
        {
                if (isPrintVerbose)
                {
                        System.out.println("done() is finish");
                }
                try
                {
                        br_right.close();
                }
                catch (IOException e)
                {
                        e.printStackTrace();
                }
                this.myprocess.stopLoop();
        }

}

时间: 2024-11-08 18:20:57

java 判断两个文件是否相同的相关文章

Java判断两个路径对应的文件是否相同

今天遇到一个bug,查了一个小时才发现是文件路径比较出了问题: 比如有两个路径:D:\dir\..\a.txt和D:\a.txt.这两个路径写法虽然不同,但是很容易知道这两个路径指向的是同一个文件.如果我们使用Java的File去判断两个路径是否相同,判断如下: File f1 = new File("D:\\dir\\..\\a.txt"); File f2 = new File("D:\\a.txt"); System.out.println(f1.getAbs

java 判断两个时间相差的天数!

package com.datedaycha;     import java.text.SimpleDateFormat;     import java.util.Calendar;     import java.util.Date;     import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;     /*      * java 判断两个时间相差的天数     1.实现目标     输入:两

Java判断两个对象是否相等的规则

Object类中的equals方法用于检测一个对象是否等于另外一个对象.在Object类中,这个方法将判断两个对象是否具有相同的引用.如果两个对象具有相同的引用,它们一定是相等的.从这点上看,将其作为默认操作也是合情合理的.然而对于多数类来说,这种判断并没有什么意义.例如,采用这种方式比较两个PrintStream对象是否相等就完全没有意义.然而,经常需要检测两个对象状态的相等性,如果两个对象的状态相等,就认为这两个对象是相等的. 例如,如果两个雇员对象的姓名.薪水和雇佣日期都一样,就认为它们是

Java 判断两个对象是否相等

一.使用 == 与 equals == : 它的作用是判断两个对象的地址是不是相等.即,判断两个对象是不是同一个对象.(基本数据类型==比较的是值,引用数据类型==比较的是内存地址) equals() : 它的作用也是判断两个对象是否相等.但它一般有两种使用情况: 情况1:类没有覆盖equals()方法.则通过equals()比较该类的两个对象时,等价于通过"=="比较这两个对象. 情况2:类覆盖了equals()方法.一般,我们都覆盖equals()方法来两个对象的内容相等:若它们的

java判断两个时间相差得天数

方法一:通过Calendar类得日期比较,在这需要考虑闰年和平年,也要考虑跨年份 /** * date2比date1多的天数 * @param date1 * @param date2 * @return */ public static int differentDays(Date date1,Date date2) { Calendar cal1 = Calendar.getInstance(); cal1.setTime(date1); Calendar cal2 = Calendar.g

java判断两集合是否相同以及求取交集,并集,差集

业务中用时需要判断两集合是否相同,所有提供一个工具方法,使用set集合的特性(元素唯一): private Map<String,Set<Integer>> getCategoryApiId(Set<Integer> oldAuthSet , Set<Integer> newAuthSet){ Map<String,Set<Integer>> categoryApiId = new HashMap(); if (oldAuthSet!

java判断两个单链表是否相交

转载于:http://blog.csdn.net/happymatilian/article/details/47811161 思路: 链表分有环链表和无环链表,如果两个链表存在相交,则只有两种可能,两个链表都无环或者都有环. (1)如果链表都无环,则先判断链表的尾指针是否一样,如果不一样,则没有相交.如果一样,则找出两个链表的长度差,将两个链表从距离尾节点同样的距离进行扫描,如果相交,则必然有一处扫描节点相同.实例数据List1:1->2->3->4->5->6->7

java 判断两个数是否异号

java 整型int占4个字节32位,两个数异或后移动31位判断结果,如果是1则异号,如果是0则同号 1 public class ShowEnviromentViarible { 2 3 public static void main(String[] args) { 4 int num1 = 1; 5 int num2 = -1; 6 System.out.println("num1 = " + num1); 7 System.out.println("num2 = &q

【转】【C#】判断两个文件是否相同

使用System.security.Cryptography.HashAlgorithm类为每个文件生成一个哈希码,然后比较两个哈希码是否相同 该哈希算法为一个文件生成一个小的二进制“指纹”,从统计学的角度来看,不同的文件不可能生成相同的哈希码 要生成一个哈希码,必须首先创建一个HashAlgorithm对象,通过HashAlgorithm.Create方法来完成.然后调用 HashAlgorithm.ComputeHash方法,它会返回一个存储哈希码的字节数组,再使用BitConverter.