我寫了這個簡短的程序,它有一個小GUI。它應該允許你輸入文本,然後你可以將它保存到一個txt文件或從先前保存的文件讀取或刪除一個現有的文件。 它的工作原理,但有一些奇怪的錯誤。有時在創建文件後,如果我嘗試刪除它,它將不會刪除該文件。InputStreams和OutputStreams
另外,我完全不知道我是否以良好的方式編寫代碼。 我在想,如果你能看看我寫的東西,並發現我應該用不同的方式編寫的弱點或區域。也許你可以看到爲什麼在創建文件後刪除文件時出現問題。我真的很茫然,我不知道該問誰。 這裏是我的代碼:
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);
}
}
如果可能的話,你應該嘗試刪除你的一些少列出相關代碼。至少你可以刪除你的進口報表。 – BlackVegetable
所以你得到你的JOptionPane說它沒有被刪除?請告訴我們,如果拒絕刪除,會發生什麼情況。 – 11684
如果這是您的意思,我可以摺疊導入代碼?或者你的意思是完全刪除它。但那麼代碼將不會運行... –