Java 如何创建具有特定名称的文件

Java 如何创建具有特定名称的文件,java,Java,我需要创建一个具有特定名称的文件,我希望该文件的名称为年、月、小时等。我使用的是LocalDateTime,我试图将文件rute与LocalDateTime连接起来 LocalDateTime ldt = LocalDateTime.now(); try { PrintWriter pw = new PrintWriter("/C:/Users/GG/Desktop/Ejercicios/"+ldt+".txt"); pw.write("prueba"); pw.wri

我需要创建一个具有特定名称的文件,我希望该文件的名称为年、月、小时等。我使用的是
LocalDateTime
,我试图将文件rute与
LocalDateTime
连接起来

LocalDateTime ldt = LocalDateTime.now();
try 
{
    PrintWriter pw = new PrintWriter("/C:/Users/GG/Desktop/Ejercicios/"+ldt+".txt");
    pw.write("prueba");
    pw.write("2");
    pw.close();
} catch (Exception e) 
{
    e.printStackTrace();
}
这就是我得到的错误:

java.io.FileNotFoundException: C:\Users\GG\Desktop\Ejercicios\2019-08-25T20:35:59.706.txt (The file name, directory name or volume label syntax is not correct)

我不确定Windows中的文件名是否可以包含
,也不清楚为什么您的格式应该遵循ISO-8601。我将使用不带符号的显式格式,而不是硬编码路径,我将相对于用户的主文件夹构建路径(这有一个系统属性,它适用于所有平台)。而且,我更喜欢
尝试使用资源
,而不是显式关闭
PrintWriter
。最后,如果目录不存在,应用程序将失败;您可以在运行时创建它们(如果它们不存在的话)。大概

LocalDateTime ldt = LocalDateTime.now();
String home = System.getProperty("user.home");
File desktop = new File(home, "Desktop");
if (!desktop.exists()) {
    desktop.mkdir();
}
File ejercicios = new File(desktop, "Ejercicios");
if (!ejercicios.exists()) {
    ejercicios.mkdir();
}
String fName = ldt.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
File outFile = new File(ejercicios, String.format("%s.txt", fName));

try (PrintWriter pw = new PrintWriter(outFile)) {
    pw.write("prueba");
    pw.write("2");
} catch (Exception e) {
    e.printStackTrace();
}

以下是路径中的保留字符:

  • <(少于)
  • >(大于)
  • :(冒号)
  • “(双引号)
  • /(正斜杠)
  • \(反斜杠)
  • |(垂直杆或管道)
  • ?(问号)
  • *(星号)
您需要在应用之前替换这些

String x = ldt;
//2019-08-25T20:35:59.706     Bad Form Path
String y = ldt.replace(':','')
//2019-08-25T203559.706       Well Form Path 
或者像这样改变格式

String x = ldt;
//2019-08-25T20:35:59.706
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy_MM_dd_HHmmss");
String y = ldt.format(formatter);
//2019_08_25_203559

尝试删除前面的
/
,即
C:
之前的那一个,然后确保
C:
驱动器上存在文件夹
\Users\GG\Desktop\Ejercicios
。文件夹存在吗?是的,文件夹存在,当我尝试创建一个没有LocalDateTime的新文件时,它创建它没有问题,但当我尝试连接ldt时,它的当它给我错误的时候。很高兴在这里