首页 > 解决方案 > 如何创建具有特定名称的文件

问题描述

我需要创建一个具有特定名称的文件,我希望文件的名称是年、月、小时等。我正在使用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)

标签: java

解决方案


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

  • <(小于)
  • >(大于)
  • : (冒号)
  • "(双引号)
  • /(正斜杠)
  • \(反斜杠)
  • | (垂直条或管)
  • ? (问号)
  • *(星号)

您需要在申请前更换这些

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

推荐阅读