Reputation: 29
I want to make it so that when I run this program I can keep entering input from the text field and it will print to the file which we are trying to write.
The code I have so far only works the first time I hit 'Enter'. After that when I do it again, it throws an exception.
Is anyone able to help me out here?
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();
}
}
Upvotes: 0
Views: 98
Reputation: 21104
The problem is pretty simple. You're calling close
on the BufferedWriter
.
else {
r.write(message);
r.newLine();
}
r.close();
The Javadoc for BufferedWriter#close
states
Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown.
You're also writing to the same file using two different objects. I recommend you to stick with one and ditch the other.
Upvotes: 2