import java.awt.*;
import java.awt.event.*;
import java.io.*;public class Main { /**
* @param args
*/
public static void main(String[] args) {
MainWindow mw = new MainWindow("FileCompare");
mw.launchWindow();
}}public class MainWindow extends Frame {
TextField t1 = new TextField();
TextField t2 = new TextField();
Button b1 = new Button("比较");
Label l1 = new Label("文件一:");
Label l2 = new Label("文件二:");
Label l3 = new Label("");
MainWindow(String s) {
super(s);
}
public void launchWindow() {
this.setLayout(new GridLayout(6, 1));
this.setBounds(500, 500, 200, 200);
this.add(l1);
this.add(t1);
this.add(l2);
this.add(t2);
this.add(b1);
this.add(l3);
this.setResizable(false);
this.setVisible(true);
b1.addActionListener(new Compare());
this.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
setVisible(false);
System.exit(0);
}
}
);
}
class Compare implements ActionListener {
FileReader fr1, fr2;
int i = 1,j = 1;
public void actionPerformed(ActionEvent e) {
if(cmp()) {
l3.setText("相同");
}
else {
l3.setText("不相同");
}
}
public boolean cmp() {
try {
fr1 = new FileReader(t1.getText());
fr2 = new FileReader(t2.getText());
} catch (IOException e) {
System.out.println("文件打开错误");
}
while(i != -1 && j != -1) {
try {
i = fr1.read();
j = fr2.read();
} catch (IOException e) {
System.out.println("文件读取错误");
}
if(i != j) {
try {
fr1.close();
fr2.close();
} catch (IOException e) {
System.out.println("文件无法关闭");
}
return false;
}
}
try {
fr1.close();
fr2.close();
} catch (IOException e) {
System.out.println("文件无法关闭");
}
return true;
}
}
}
运行时候有点问题,两个相同文件一比较,显示的就一直是相同(就算换两个不同文件比较也是)。
public boolean cmp() {
i=1;//复位
j=1;//复位
try {
fr1 = new FileReader(t1.getText());
fr2 = new FileReader(t2.getText());
} catch (IOException e) {
System.out.println("文件打开错误");
}