在Java中创建具有动态名称的文件时,获取语法是不正确的错误
我正在编写一个简单的Java应用程序,它基本上记录串行设备的输出(有点像PuttY)。到目前为止,数据流和显示工作正常,我正在进入程序的文件创建和编写部分,我正在测试一些我读到的关于创建文件的代码:在Java中创建具有动态名称的文件时,获取语法是不正确的错误,java,netbeans,Java,Netbeans,我正在编写一个简单的Java应用程序,它基本上记录串行设备的输出(有点像PuttY)。到目前为止,数据流和显示工作正常,我正在进入程序的文件创建和编写部分,我正在测试一些我读到的关于创建文件的代码: public void createNewFile() { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss"); String newFileName = dateFo
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=新文件(fullFilePath)
这是owrking。谢谢Kornejew一些操作系统不允许文件名中使用冒号(
:
)。你认为新文件(“C:\\Boxtest-%s.txt”,newFileName)”有什么作用,你为什么相信?提示:它不会将%s
替换为newFileName
。谢谢。你说得对。但是,现在我用下划线(u)而不是冒号替换了格式,我得到了一个错误:“系统找不到指定的路径”字符串替换在这里不起作用。尝试类似字符串newFileName=“C:\\Boxtest-”+dateFormat.format(System.currentTimeMillis())+“.txt”的操作;请尝试{File newFile=newFile(newFileName);…接下来可能会出现“拒绝访问”错误。您可以更改到“C:\temp\”目录以解决此问题。谢谢Kornejew,这很有效。我用有效的代码更新了新的答案。