如何用年月日时分秒命名文件?Java代码示例
Java可以很方便地获取当前的日期和时间,例如 2023-08-31 和 10:30:20。但是文件名不能包含特殊字符。如果要以年月日时分秒命名文件,可以使用以下方法:
- 使用Java中的SimpleDateFormat类对日期和时间进行格式化,并将其作为文件名的一部分。例如:
import java.text.SimpleDateFormat;
import java.util.Date;
public class FileNameGenerator {
public static void main(String[] args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
Date now = new Date();
String fileName = dateFormat.format(now) + ".txt";
System.out.println(fileName);
}
}
输出结果可能是:20230831_103020.txt
- 如果希望在文件名中使用连接符号(如'-'和':'),可以将特殊字符替换为其他字符,例如使用下划线'_'代替连接符号。例如:
import java.text.SimpleDateFormat;
import java.util.Date;
public class FileNameGenerator {
public static void main(String[] args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now = new Date();
String formattedDate = dateFormat.format(now);
String fileName = formattedDate.replaceAll("[-:]", "_" ) + ".txt";
System.out.println(fileName);
}
}
输出结果可能是:2023_08_31_10_30_20.txt
请注意,不同的操作系统对文件名所允许的特殊字符可能有所不同。因此,为了确保文件名的可移植性和避免可能的问题,最好仅使用字母、数字和下划线等常规字符来命名文件。
原文地址: https://www.cveoy.top/t/topic/qAvl 著作权归作者所有。请勿转载和采集!