2017-04-03 52 views
0

我试着做一个GUI程序,将采取两个文件,并比较其比较两个文件的JPanel

,以及它们是否符合其将显示匹配,如果没有它会显示两个文件的不同行。

我的问题是我将如何罚款两个文件 之间的不同线路以及如​​何在面板中打印结果?

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); 
    } 

} 
+0

你应该缩小你遇到的问题。一步一步解决问题。例如。首先确定两个文件是否相等,然后展开列出所有不同的行等。 – Paul

回答

0

使用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")一样简单。