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

早过忘川 提交于 2019-12-31 07:43:07

问题


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.


回答1:


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:


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:\...).



来源:https://stackoverflow.com/questions/41199422/creating-a-text-file-with-the-current-date-and-time-as-the-file-name-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!