我想这样做,以便在运行该程序时,我可以继续从文本字段输入输入,它将打印到我们尝试编写的文件中。
到目前为止,我拥有的代码仅在我第一次按Enter键时有效。 之后,当我再次执行此操作时,它将引发异常。
有人可以在这里帮助我吗?
public static void main(String [] args) throws IOException {
//creates file or opens existing file
File f = new File("C:/Users/User/Desktop/course.txt");
Scanner sc = new Scanner(System.in);
FileWriter w = new FileWriter(f.getAbsoluteFile(), true);
BufferedWriter r = new BufferedWriter(w);
//GUI Setting
JFrame frame = new JFrame();
JLabel text = new JLabel();
JLabel results = new JLabel();
JPanel panel = new JPanel();
JTextField textField = new JTextField();
textField.setPreferredSize(new Dimension(450, 30));
text.setText("Enter \"END\" to terminate program OR \"CLEAR ALL\" to delete everything in the file");
frame.getContentPane().add(panel);
frame.setSize(new Dimension(500, 150));
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Course");
frame.setResizable(true);
frame.setVisible(true);
panel.add(text);
panel.add(textField);
panel.add(results);
//action listener for textfield when user hits enter
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String message;
message = textField.getText();
try {
if(message.contains("END")) {
System.exit(0);
}
if(message.contains("CLEAR ALL")) {
clear();
}
else {
r.write(message);
r.newLine();
}
r.close();
}catch(IOException e1) {
results.setText("Error");
}
textField.setText("");
}
}
);
//set focus to text field once GUI is opened
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textField.requestFocus();
}
});
}
//clear function to empty the file
private static void clear() throws FileNotFoundException {
File f = new File("C:/Users/User/Desktop/course.txt");
PrintWriter w = new PrintWriter(f);
w.print("");
w.close();
}
}
答案 0 :(得分:1)
问题很简单。您正在close
上呼叫BufferedWriter
。
else {
r.write(message);
r.newLine();
}
r.close();
BufferedWriter#close
状态的Javadoc
关闭流,先冲洗。 流关闭后, 进一步的write()或flush()调用将导致IOException 抛出。
您还将使用两个不同的对象写入同一文件。我建议您坚持一个而放弃另一个。