使用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.setBackground(Color.red);
- 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 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);
- // }
- }
- 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();
- }
- }