比较 Jpanel 中的两个文件



我试图做一个GUI程序,它将接受两个文件并进行比较

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

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

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( "nnnn 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")更新其内容一样简单。

最新更新