用动态名称在Java中创建文件,获取语法错误错误

问题描述

我正在编写一个简单的Java应用程序,该应用程序基本上记录了串行设备(有点像PuttY)的输出。到目前为止,数据的流式传输和显示正在工作,我正在进入文件创建和编写程序的一部分的过程,并且正在测试一些有关创建文件代码

public void createNewFile() {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
    String newFileName = dateFormat.format(System.currentTimeMillis());
    try {
        File newFile = new File("C:\\Boxtest-%s.txt",newFileName);
        boolean fvar = newFile.createNewFile();
        if (fvar) {
            System.out.println("File created successfully");
            updateStatus("File created successfully!");
        }
        else {
            System.out.println("File already present");
            updateStatus("File already exists");
        }
        
    } catch (IOException e) {
        System.out.println("Exception!");
        updateStatus(e.getLocalizedMessage());
    }
    
}

查看错误消息的状态时,出现错误文件名,目录名或卷标语法不正确”。
我认为这是由于文件名中包含变量? (“ C:\ Boxtest-%s”,newFileName),但是每次启动按钮并使用文件名中的当前日期/时间来避免覆盖旧文件时,如何使它创建一个文件

解决方法

问题在于您的日期格式中的冒号。 Windows中不允许使用它们作为文件名。

您可以使用System.currentTimeMillis();没有格式或没有冒号的格式。

,

好的,因此,有人建议对此进行修复:

  • 由于操作系统不允许从文件名中删除冒号。

  • 下面的新代码段:

    fullFilePath = String.format(“ C:\ boxtest \%s-Boxtest.txt”,newFileName); File newFile = new File(fullFilePath);

显然,%s在New File标注中没有被newFileName代替,所以我不得不使用格式字符串,然后在New File标注中使用完整路径。
现在已经有了。谢谢您Kornejew