在 Java 中创建一个以当前日期和时间作为文件名的文本文件

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

我正在尝试创建一个文本文件并使用 Java 添加一些详细信息,当在我的 GUI 应用程序中单击一个按钮时,文本文件的名称必须是当前日期和时间,并且文本文件的位置必须是相对的。这是我用来执行此操作的代码片段。

        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);
            }
       }

不幸的是,当我 运行 上面的代码时,我得到以下错误:

我找不到问题,请告诉我我做错了什么。

猜想:

  1. 您的操作系统不允许在文件名中使用 / 字符
  2. 或者它认为 / 分隔目录;换句话说:你正试图在一个子目录中创建一个文件......可能不存在

和无关,但也很重要:你不应该混合这样的东西。您应该将创建和写入该文件的代码 放入 它自己的实用程序 class 中;而不是将其推送到您的 UI 相关代码中。

你看,如果你在这里创建了一个助手class;对那个进行一些单元测试也会 容易;以确保它做你期望它做的事。

文件系统对哪些字符可以进入文件名有限制。例如,正如@lordvlad 所说,斜杠用于在成功目录之间进行划分。此外,在 Windows 中,: 用于分隔驱动器名称(即 C:\...)。