繁体   English   中英

比较Jpanel中的两个文件

[英]Compare two files in Jpanel

我正在尝试做一个将两个文件进行比较的GUI程序

如果它们匹配,它将显示match,如果不匹配,它将显示两个文件之间的不同行。

我的问题是如何对两个文件之间的不同行进行罚款,以及如何在面板中打印结果?

public class Q25 extends JPanel implements ActionListener
{
    File file1;
    File file2;
    JButton compare=new JButton("Compare");
    JButton fileButton = new JButton("First File");
    JButton fileButton1 = new JButton("Secound File");
     JLabel labelA;

    Q25()
    {
        add(fileButton);
        add(fileButton1);
        fileButton.addActionListener(this);
        fileButton1.addActionListener(this);

        add(compare);

        labelA = new JLabel();
        labelA.setText( "\n\n\n\n result : " );

        add(labelA);
    }

    @Override
    public void actionPerformed(ActionEvent e) 
    {
        if(e.getSource()==fileButton) 
        {
            JFileChooser chooser = new JFileChooser();
            int option = chooser.showOpenDialog(Q25.this);
            if (option == JFileChooser.APPROVE_OPTION)
            {
                if (!chooser.getSelectedFile().canRead())
JOptionPane.showMessageDialog( null,"The file is NOT readable by the current application!","ERROR" , JOptionPane.ERROR_MESSAGE );

            }
        }

        if(e.getSource()==fileButton1) 
        {
            JFileChooser chooser1 = new JFileChooser();
            int option1 = chooser1.showOpenDialog(Q25.this);
            if (option1 == JFileChooser.APPROVE_OPTION)
            {
                if (!chooser1.getSelectedFile().canRead())
JOptionPane.showMessageDialog( null, "The file is NOT readable by the current application!", "ERROR", JOptionPane.ERROR_MESSAGE );

            }
        }


        if(file1==file2)
        {

        }else{

        }

    }
    public static void main(String[]args)
    {
        JFrame frame1 = new JFrame("compare files ");
        frame1.add(new Q25());
        frame1.setLayout(new GridLayout());
        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame1.setSize(250, 400);
        frame1.setVisible(true);
    }

}

使用Files.readAllBytes()获取字节数组,然后将它们与Arrays.equals()比较。 例如:

byte[] file1Bytes = Files.readAllBytes(file1);
byte[] file2Bytes = Files.readAllBytes(file2);
if(Arrays.equals(file1Bytes, file2Bytes){
    //match
}
else{
    //no match
}

请记住,例如,如果文件看起来相同,但文件末尾包含一个额外的换行符,则将不返回任何匹配项。

现在,用于显示结果; 这就像制作JLabel并使用label.setText("whatever")更新其内容一样简单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM