I am trying to create a text file and add some details into it using Java when a button is clicked in my GUI application, the name of the text file has to be the current date and time and the location of the text file has to be relative. Here is the code snippet I used to do this.
public void actionPerformed(ActionEvent e){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd_HH:mm:ss");
Date date = new Date();
String fileName = dateFormat.format(date) + ".txt";
File file = new File(fileName);
PrintWriter pw;
try{
if(file.createNewFile()){
pw = new PrintWriter(file);
//Write Details To Created Text File Here
JOptionPane.showMessageDialog(null, "The Statistics have successfully been saved to the file: "
+ fileName);
}else{
JOptionPane.showMessageDialog(null, "The save file " + fileName
+ " already exists, please try again in a while.");
}
}catch(IOException exception){
JOptionPane.showMessageDialog(null, exception + ", file name:- " + fileName);
}catch(Exception exception){
JOptionPane.showMessageDialog(null, exception);
}
}
Unfortunately when I run the above code I get the following error:
I cannot find the problem, please tell me what I am doing wrong.
Guessing: either
And unrelated, but important too: you should not mix such things. You should put the code that creates and writes that file into its own utility class; instead of pushing it into your UI related code.
You see, if you had created a helper class here; it would also be much easier to do some unit-testing on that one; to ensure it does what you expect it to do.