且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

java 判断两个文件是否相同

更新时间:2021-11-03 10:14:04

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

我的做法是
(1)先比较两个文件内容的长度;
(2)在长度相同的情况下,再比较两个文件的MD5值。

java 判断两个文件是否相同
【create md5】按钮用于生成source file的文件内容长度和MD5值。
运行主类:CheckSameApp 
Java代码  java 判断两个文件是否相同
  1. package com.hw.main;  
  2.   
  3. import java.awt.BorderLayout;  
  4. import java.awt.Container;  
  5. import java.awt.Dimension;  
  6. import java.awt.GridBagConstraints;  
  7. import java.awt.GridBagLayout;  
  8. import java.awt.Insets;  
  9. import java.awt.Toolkit;  
  10. import java.awt.event.ActionEvent;  
  11. import java.awt.event.ActionListener;  
  12. import java.io.File;  
  13.   
  14. import javax.swing.JButton;  
  15. import javax.swing.JFileChooser;  
  16. import javax.swing.JFrame;  
  17. import javax.swing.JLabel;  
  18. import javax.swing.JPanel;  
  19. import javax.swing.JTextField;  
  20.   
  21. import com.common.util.SystemUtil;  
  22. import com.swing.dialog.DialogUtil;  
  23. import com.swing.messagebox.GUIUtil23;  
  24.   
  25. public class CheckSameApp extends JFrame  
  26. {  
  27.     private static final long serialVersionUID = 1644076682819874235L;  
  28.     private JTextField        sourceFileTF;  
  29.     private JButton           browserSourceBtn;  
  30.     private JTextField        targetFileTF;  
  31.     private JButton           createmd5Button  = null;  
  32.     private JButton           checkmd5Btn      = null;  
  33.     private JButton           browserTargetBtn = null;  
  34.     /*** 
  35.      * MD5 of last file 
  36.      */  
  37.     private String            result           = null;  
  38.     private long              size_of_file     = 0;  
  39.     private JButton           compareBtn       = null;  
  40.     private File              srcfile          = null;  
  41.     private File              targfile         = null;  
  42.     protected static String   MESG_DIFF        = "[failed:] they are different";  
  43.     protected static String   MESG_SAME        = "[successfully:] they are same completely";  
  44.   
  45.     public static void main(String[] args)  
  46.     {  
  47.         CheckSameApp app = new CheckSameApp();  
  48.         app.launchFrame();  
  49.     }  
  50.   
  51.     public void launchFrame()  
  52.     {  
  53.         this.setTitle("Compare two files by MD5");  
  54.         Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();  
  55.         this.setSize(700200);  
  56.         Dimension framesize = this.getSize();  
  57.         int x = (int) screensize.getWidth() / 2 - (int) framesize.getWidth()  
  58.             / 2;  
  59.         int y = (int) screensize.getHeight() / 2 - (int) framesize.getHeight()  
  60.             / 2;  
  61.         this.setLocation(x, y);  
  62.         Container c = this.getContentPane();  
  63.         layout(c);  
  64.         this.setVisible(true);  
  65.         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  66.     }  
  67.   
  68.     /*** 
  69.      * setting menu 
  70.      */  
  71.       
  72.   
  73.     public void layout(Container c)  
  74.     {  
  75.         //        setMenu2();  
  76.         JPanel mainPane = new JPanel();  
  77.         GridBagLayout gridBagLayout = new GridBagLayout();  
  78.         gridBagLayout.columnWidths = new int[]  
  79.         { 2080/*between source file and text field*/300600 };  
  80.         gridBagLayout.rowHeights = new int[]  
  81.         { 17000000002500 };  
  82.         gridBagLayout.columnWeights = new double[]  
  83.         { 0.00.01.01.0, Double.MIN_VALUE };  
  84.         gridBagLayout.rowWeights = new double[]  
  85.         { 0.00.00.00.00.00.01.00.00.01.01.0,  
  86.             Double.MIN_VALUE };  
  87.   
  88.         mainPane.setLayout(gridBagLayout);  
  89.         JLabel ftpServerLb = new JLabel("source file");  
  90.         GridBagConstraints gbc_setConnectionsLabel = new GridBagConstraints();  
  91.         gbc_setConnectionsLabel.anchor = GridBagConstraints.WEST;  
  92.         gbc_setConnectionsLabel.insets = new Insets(0055);  
  93.         gbc_setConnectionsLabel.gridx = 1;  
  94.         gbc_setConnectionsLabel.gridy = 1;  
  95.         mainPane.add(ftpServerLb, gbc_setConnectionsLabel);  
  96.         //        dialog.add(ftpserverTF);  
  97.   
  98.         sourceFileTF = new JTextField();  
  99.         if (!SystemUtil.isWindows)  
  100.         {  
  101.             sourceFileTF.setText("/home/whuang2/bin/ab.txt");  
  102.         }  
  103.         else  
  104.         {  
  105.             sourceFileTF.setText("");  
  106.         }  
  107.         GridBagConstraints gbc_connectionsTF = new GridBagConstraints();  
  108.         gbc_connectionsTF.fill = GridBagConstraints.HORIZONTAL;  
  109.         gbc_connectionsTF.insets = new Insets(0055);  
  110.         gbc_connectionsTF.gridx = 2;  
  111.         gbc_connectionsTF.gridy = 1;  
  112.         mainPane.add(sourceFileTF, gbc_connectionsTF);  
  113.   
  114.         browserSourceBtn = new JButton("browser source");  
  115.         GridBagConstraints gbc_browserSourceBtn = new GridBagConstraints();  
  116.         gbc_browserSourceBtn.fill = GridBagConstraints.EAST;  
  117.         gbc_browserSourceBtn.insets = new Insets(0055);  
  118.         gbc_browserSourceBtn.gridx = 3;  
  119.         gbc_browserSourceBtn.gridy = 1;  
  120.         mainPane.add(browserSourceBtn, gbc_browserSourceBtn);  
  121.         browserSourceBtn.addActionListener(new ActionListener()  
  122.         {  
  123.             @Override  
  124.             public void actionPerformed(ActionEvent e)  
  125.             {  
  126.                 //                System.out.println("source");  
  127.                 boolean isSuccess = DialogUtil.browser3(sourceFileTF,  
  128.                     JFileChooser.FILES_ONLY, CheckSameApp.this);  
  129.                 //                if (isSuccess)  
  130.                 //                {  
  131.                 //                    targetFileTF.setText(SystemUtil.getParentDir(sourceFileTF  
  132.                 //                            .getText()));  
  133.                 //                }  
  134.             }  
  135.         });  
  136.   
  137.         JPanel buttonPane = new JPanel();  
  138.         //        buttonPane.setBackground(Color.red);  
  139.         GridBagConstraints gbc_buttonPane = new GridBagConstraints();  
  140.         gbc_buttonPane.fill = GridBagConstraints.HORIZONTAL;  
  141.         gbc_buttonPane.insets = new Insets(0055);  
  142.         gbc_buttonPane.gridx = 2;  
  143.         gbc_buttonPane.gridy = 2;  
  144.         mainPane.add(buttonPane, gbc_buttonPane);  
  145.   
  146.         createmd5Button = new JButton("create md5");  
  147.         checkmd5Btn = new JButton("check");  
  148.         checkmd5Btn.setEnabled(false);  
  149.         buttonPane.add(createmd5Button);  
  150.         buttonPane.add(checkmd5Btn);  
  151.         createmd5Button.addActionListener(new ActionListener()  
  152.         {  
  153.             @Override  
  154.             public void actionPerformed(ActionEvent e)  
  155.             {  
  156.                 if (!validate3(true))  
  157.                 {  
  158.                     return;  
  159.                 }  
  160.                 sourceFileTF.setEditable(false);  
  161.                 new Thread(new Runnable()  
  162.                 {  
  163.                     @Override  
  164.                     public void run()  
  165.                     {  
  166.                         createmd5Button.setEnabled(false);  
  167.                         size_of_file = srcfile.length();  
  168.                         result = SystemUtil.getFileMD5(srcfile);  
  169.                         checkmd5Btn.setEnabled(true);  
  170.                         createmd5Button.setEnabled(true);  
  171.                     }  
  172.                 }).start();  
  173.   
  174.                   
  175.             }  
  176.         });  
  177.   
  178.         checkmd5Btn.addActionListener(new ActionListener()  
  179.         {  
  180.             @Override  
  181.             public void actionPerformed(ActionEvent e)  
  182.             {  
  183.                 //                if (!validate3(true))  
  184.                 //                {  
  185.                 //                    return;  
  186.                 //                }  
  187.                 long size_of_file2 = srcfile.length();  
  188.                 if (size_of_file2 != size_of_file)  
  189.                 {  
  190.                     System.out.println("by size");  
  191.                     GUIUtil23.errorDialog(MESG_DIFF);  
  192.                     return;  
  193.                 }  
  194.   
  195.                 new Thread(new Runnable()  
  196.                 {  
  197.                     @Override  
  198.                     public void run()  
  199.                     {  
  200.                         checkmd5Btn.setEnabled(false);  
  201.                         String result2;  
  202.                         sourceFileTF.setEditable(true);  
  203.                         result2 = SystemUtil.getFileMD5(srcfile);  
  204.                         boolean isSame2=isSame(result2, result);  
  205.                         checkmd5Btn.setEnabled(true);  
  206.                         if (isSame2)  
  207.                         {  
  208.                             GUIUtil23.infoDialog(MESG_SAME);  
  209.                         }  
  210.                         else  
  211.                         {  
  212.                             GUIUtil23.errorDialog(MESG_DIFF);  
  213.                         }  
  214.                     }  
  215.                 }).start();  
  216.                   
  217.             }  
  218.         });  
  219.   
  220.         JLabel targetLabel = new JLabel("target file");  
  221.         GridBagConstraints gbc_driveClassLabel = new GridBagConstraints();  
  222.         gbc_driveClassLabel.anchor = GridBagConstraints.WEST;  
  223.         gbc_driveClassLabel.insets = new Insets(0055);  
  224.         gbc_driveClassLabel.gridx = 1;  
  225.         gbc_driveClassLabel.gridy = 3;  
  226.         mainPane.add(targetLabel, gbc_driveClassLabel);  
  227.   
  228.         targetFileTF = new JTextField();  
  229.         if (!SystemUtil.isWindows)  
  230.         {  
  231.             targetFileTF.setText("/home/whuang2/bin/wh_dos2unix");  
  232.         }  
  233.         GridBagConstraints gbc_driveClassTF = new GridBagConstraints();  
  234.         gbc_driveClassTF.insets = new Insets(0055);  
  235.         gbc_driveClassTF.fill = GridBagConstraints.HORIZONTAL;  
  236.         gbc_driveClassTF.gridx = 2;  
  237.         gbc_driveClassTF.gridy = 3;  
  238.         mainPane.add(targetFileTF, gbc_driveClassTF);  
  239.         targetFileTF.setColumns(10);  
  240.   
  241.         browserTargetBtn = new JButton("browser target");  
  242.         GridBagConstraints gbc_browserTargetBtn = new GridBagConstraints();  
  243.         gbc_browserTargetBtn.fill = GridBagConstraints.EAST;  
  244.         gbc_browserTargetBtn.insets = new Insets(0055);  
  245.         gbc_browserTargetBtn.gridx = 3;  
  246.         gbc_browserTargetBtn.gridy = 3;  
  247.         mainPane.add(browserTargetBtn, gbc_browserTargetBtn);  
  248.         browserTargetBtn.addActionListener(new ActionListener()  
  249.         {  
  250.             @Override  
  251.             public void actionPerformed(ActionEvent e)  
  252.             {  
  253.                 //                System.out.println("target");  
  254.                 DialogUtil.browser3(targetFileTF,  
  255.                     JFileChooser.FILES_AND_DIRECTORIES, CheckSameApp.this);  
  256.             }  
  257.         });  
  258.         compareBtn = new JButton("compare");  
  259.         GridBagConstraints gbc_runBtn = new GridBagConstraints();  
  260.         gbc_runBtn.fill = GridBagConstraints.EAST;  
  261.         gbc_runBtn.insets = new Insets(0055);  
  262.         gbc_runBtn.gridx = 4;  
  263.         gbc_runBtn.gridy = 3;  
  264.         mainPane.add(compareBtn, gbc_runBtn);  
  265.   
  266.         compareBtn.addActionListener(new ActionListener()  
  267.         {  
  268.   
  269.             @Override  
  270.             public void actionPerformed(ActionEvent e)  
  271.             {  
  272.                 if (!validate3(false))  
  273.                 {  
  274.                     return;  
  275.                 }  
  276.   
  277.                 long size_of_targfile = targfile.length();  
  278.                 long size_of_srcfile = srcfile.length();  
  279.                 if (size_of_targfile != size_of_srcfile)  
  280.                 {  
  281.                     System.out.println("by size");  
  282.                     GUIUtil23.errorDialog(MESG_DIFF);  
  283.                     return;  
  284.                 }  
  285.                 new Thread(new Runnable()  
  286.                 {  
  287.                     @Override  
  288.                     public void run()  
  289.                     {  
  290.                         compareBtn.setEnabled(false);  
  291.                         String result_source = SystemUtil.getFileMD5(srcfile);  
  292.                         String result_target;  
  293.                         result_target = SystemUtil.getFileMD5(targfile);  
  294.                         boolean isSame2=isSame(result_source, result_target);  
  295.                         compareBtn.setEnabled(true);  
  296.                         if (isSame2)  
  297.                         {  
  298.                             GUIUtil23.infoDialog(MESG_SAME);  
  299.                         }  
  300.                         else  
  301.                         {  
  302.                             GUIUtil23.errorDialog(MESG_DIFF);  
  303.                         }  
  304.   
  305.                     }  
  306.                 }).start();  
  307.             }  
  308.         });  
  309.   
  310.         c.add(mainPane, BorderLayout.CENTER);  
  311.         //        System.out.println(c.getLayout());  
  312.         //new JScrollPane(text)  
  313.     }  
  314.   
  315.     //    private String create_md5(String filePath)  
  316.     //    {  
  317.     //        try  
  318.     //        {  
  319.     //            return create_md5(filePath, null);  
  320.     //        }  
  321.     //        catch (IOException e)  
  322.     //        {  
  323.     //            e.printStackTrace();  
  324.     //        }  
  325.     //        return null;  
  326.     //    }  
  327.   
  328.     /*** 
  329.      *  
  330.      * @param result_source : such as b79898bb7907648871745cd5422c79ce   /home/whuang2/bin/ab.txt 
  331.      * @param result_target 
  332.      * @return 
  333.      */  
  334.     private boolean isSame(String result_source, String result_target)  
  335.     {  
  336.         if (result_source == null || result_target == null)  
  337.         {  
  338.             return false;  
  339.         }  
  340.         return (result_source.split("[ \t]")[0].equals(result_target  
  341.                 .split("[ \t]")[0]));  
  342.     }  
  343.   
  344.   
  345.     private boolean validate3(boolean isSelf)  
  346.     {  
  347.         String sourceFile = sourceFileTF.getText();  
  348.         String targetFile_dir = targetFileTF.getText();  
  349.         if (sourceFile == null || sourceFile.equals(""))  
  350.         {  
  351.             GUIUtil23  
  352.                     .warningDialog("source file can not be empty,please select again  !");  
  353.             sourceFileTF.requestFocus();//focus  
  354.   
  355.             return false;  
  356.         }  
  357.         if (!isSelf)  
  358.         {  
  359.             if (targetFile_dir == null || targetFile_dir.equals(""))  
  360.             {  
  361.                 GUIUtil23  
  362.                         .warningDialog("target file can not be empty,please select again !");  
  363.                 targetFileTF.requestFocus();//focus  
  364.                 return false;  
  365.             }  
  366.         }  
  367.         //                System.out.println("source file:" + sourceFile);  
  368.         //                System.out.println("target file:" + targetFile_dir);  
  369.         srcfile = new File(sourceFile);  
  370.         if (!srcfile.exists())  
  371.         {  
  372.             GUIUtil23  
  373.                     .warningDialog("source file does not exist,please select again!");  
  374.             sourceFileTF.requestFocus();//focus  
  375.             sourceFileTF.selectAll();  
  376.             return false;  
  377.         }  
  378.         if (srcfile.exists() && srcfile.isDirectory())  
  379.         {  
  380.             GUIUtil23  
  381.                     .warningDialog("source file can not be directory,please select again!");  
  382.             sourceFileTF.requestFocus();//focus  
  383.             sourceFileTF.selectAll();  
  384.             return false;  
  385.         }  
  386.         if (!isSelf)  
  387.         {  
  388.             {  
  389.                 targfile = new File(targetFile_dir);  
  390.                 if (!targfile.exists())  
  391.                 {  
  392.                     GUIUtil23  
  393.                             .warningDialog("target file does not exist,please select again!");  
  394.                     targetFileTF.requestFocus();//focus  
  395.                     targetFileTF.selectAll();  
  396.                     return false;  
  397.                 }  
  398.                 if (targfile.exists() && targfile.isDirectory())  
  399.                 {  
  400.                     GUIUtil23  
  401.                             .warningDialog("target file can not be directory,please select again!");  
  402.                     targetFileTF.requestFocus();//focus  
  403.                     targetFileTF.selectAll();  
  404.                     return false;  
  405.                 }  
  406.             }  
  407.         }  
  408.         return true;  
  409.   
  410.     }  
  411.   
  412.     //    public static void main2(String[] args)  
  413.     //    {  
  414.     //        String sourceFile = "/home/whuag2/workspace/io0007-find_progess/src/com/cmd/dos/hw/util/CMDUtil.java";  
  415.     //        md5(sourceFile);  
  416.     //    }  
  417.   
  418. }  
 swingwork类:CheckSameSwingWorker
Java代码  java 判断两个文件是否相同
  1. package com.hw.util;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStreamReader;  
  6. import java.util.List;  
  7.   
  8. import javax.swing.SwingWorker;  
  9.   
  10. import com.common.util.MyProcess;  
  11.   
  12. public class CheckSameSwingWorker extends SwingWorker<Boolean, Character>  
  13. {  
  14.     private BufferedReader br_right       = null;  
  15.     private BufferedReader br_error       = null;  
  16.     private MyProcess      myprocess      = null;  
  17.     private char           word           = ' ';  
  18.     private int            tmp            = 0;  
  19.     private boolean        isPrintVerbose = false;  
  20.     private StringBuffer   stringbuf      = new StringBuffer();  
  21.   
  22.     public CheckSameSwingWorker(MyProcess myprocess, BufferedReader br)  
  23.     {  
  24.         this.br_right = br;  
  25.         this.myprocess = myprocess;  
  26.   
  27.     }  
  28.   
  29.     public CheckSameSwingWorker(MyProcess myprocess)  
  30.     {  
  31.         this.myprocess = myprocess;  
  32.         br_right = new BufferedReader(new InputStreamReader(  
  33.             myprocess.getInputStream()), 4096);  
  34.         br_error = new BufferedReader(new InputStreamReader(  
  35.             myprocess.getErrorStream()), 4096);  
  36.     }  
  37.   
  38.     @Override  
  39.     protected Boolean doInBackground() throws Exception  
  40.     {  
  41.         while ((tmp = br_right.read()) != -1)  
  42.         {  
  43.             word = (char) tmp;  
  44.             publish(word);  
  45.         }  
  46.         while ((tmp = br_error.read()) != -1)  
  47.         {  
  48.             word = (char) tmp;  
  49.             publish(word);  
  50.         }  
  51.         if (isPrintVerbose)  
  52.         {  
  53.             System.out.println("doInBackground() over");  
  54.         }  
  55.         return true;  
  56.     }  
  57.   
  58.     @Override  
  59.     protected void process(List<Character> chunks)  
  60.     {  
  61.         for (char temp : chunks)  
  62.         {  
  63.             {  
  64. //                System.out.print(temp);  
  65.                 this.stringbuf.append(temp);  
  66.             }  
  67.         }  
  68.     }  
  69.   
  70.     public StringBuffer getStringbuf()  
  71.     {  
  72.         return stringbuf;  
  73.     }  
  74.   
  75.     /*** 
  76.      * main thread can't execute next command(below waitFor())  
  77.      * until done() is executed 
  78.      */  
  79.     @Override  
  80.     protected void done()  
  81.     {  
  82.         if (isPrintVerbose)  
  83.         {  
  84.             System.out.println("done() is finish");  
  85.         }  
  86.         try  
  87.         {  
  88.             br_right.close();  
  89.         }  
  90.         catch (IOException e)  
  91.         {  
  92.             e.printStackTrace();  
  93.         }  
  94.         this.myprocess.stopLoop();  
  95.     }  
  96.   
  97. }