我写了这个有一个很小的 GUI 的短程序。它应该允许您输入文本,然后您可以将其保存到 txt 文件或从以前保存的文件中读取或删除现有文件。它可以工作,但有一些奇怪的错误。有时创建文件后,如果我尝试删除它,它不会删除该文件。
另外,我完全不确定我是否以一种好的方式编写了代码。我想知道你是否可以看看我写的内容并找到我应该以不同方式写的弱点或领域。而且也许您可以看到为什么在创建文件后删除文件会出现问题。我真的很茫然,我不知道该问谁。这是我的代码:
public class InputOutout extends JFrame{
private static final long serialVersionUID = -7073762217756427192L;
JLabel label;
JTextField tf;
JButton buttonAdd;
JButton buttonDisplay;
JButton buttonErase;
public InputOutout() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
setLayout(new FlowLayout());
label = new JLabel("Enter text");
add(label);
tf = new JTextField(10);
add(tf);
buttonAdd = new JButton("Press to save to file");
add(buttonAdd);
buttonDisplay = new JButton("Press to display file content");
add(buttonDisplay);
buttonErase = new JButton("Press to erase file");
add(buttonErase);
eventAdd add = new eventAdd();
eventDisplay remove = new eventDisplay();
eventErase erase = new eventErase();
buttonAdd.addActionListener(add);
buttonDisplay.addActionListener(remove);
buttonErase.addActionListener(erase);
}
private class eventAdd implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
String word = tf.getText()+ " ";
FileWriter stream = new FileWriter("text.txt",true);
BufferedWriter out = new BufferedWriter(stream);
out.append(word);
out.close();
tf.setText("");
} catch (Exception ex){
JOptionPane.showMessageDialog(null,ex.getMessage());
}
}
}
private class eventDisplay implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
FileReader stream = new FileReader("text.txt");
BufferedReader in = new BufferedReader(stream);
String text = in.readLine();
JOptionPane.showMessageDialog(null, text);
stream.close();
} catch (Exception ex){
JOptionPane.showMessageDialog(null,ex.getMessage());
}
}
}
private class eventErase implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
File file = new File("text.txt");
boolean success = file.delete();
if (!success) {
JOptionPane.showMessageDialog(null, "File was not deleted");
} else {
JOptionPane.showMessageDialog(null, "File was deleted");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,ex.getMessage());
}
}
}
public static void main(String[] args) {
InputOutout gui = new InputOutout();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(350,100);
gui.setTitle("SuperWORD 2013");
gui.setVisible(true);
}
}