Creating a text file with the current date and time as the file name in Java

2.3k views Asked by At

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:

enter image description here

I cannot find the problem, please tell me what I am doing wrong.

2

There are 2 answers

2
GhostCat On BEST ANSWER

Guessing: either

  1. your operating system doesn't allow to use the / character in file names
  2. or it thinks that / separates directories; in other words: you are trying to create a file in a subdirectory ... that probably doesn't exist

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.

2
Scott Hunter On

Filesystems have limitations on what characters can go into file names. For example, as @lordvlad says, slashes are used to divide between success directories. Also, in Windows, the : is used to separate the drive name (i.e. C:\...).