gpt4 book ai didi

java - 如何每天创建新目录,并将其名称作为当前日期

转载 作者:行者123 更新时间:2023-11-30 06:07:46 24 4
gpt4 key购买 nike

Date dir = new java.util.Date(System.currentTimeMillis());
String baseDir = "/home/gaurav/usr/logs/ESBegin/";
String newDir = createDateBasedDirectory(baseDir, dir);

Logger logger = Logger.getLogger("MyLog1");
FileHandler fh;

try {

// This block configure the logger with handler and formatter
fh = new FileHandler(newDir+"/data.log");
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);

// the following statement is used to log any messages
logger.info(stringifiedJson);

} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

这将创建今天日期的文件夹,但我想每天创建新文件夹并将日志文件存储在新文件夹中....意味着每天的文件夹必须包含当天的日志文件我有以下方法来创建文件夹

 public static String createDateBasedDirectory(String baseDirectory, Date argDate) {
String newDir = null;

if (baseDirectory != null && argDate != null) {
try {
String format = "yyyy-MM-dd";
DateFormat dateFormatter = new SimpleDateFormat(format);
String date = dateFormatter.format(argDate);
File f = new File(baseDirectory);
File files[] = f.listFiles();
String dir = null;
int baseDirLength = baseDirectory.length();
int checkingLength = baseDirLength + format.length() + 3;

int maxSeqNo = 0;

for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
dir = files[i].toString();
if (dir.length() == checkingLength) {
String existingDirDate = dir.substring(baseDirLength, baseDirLength + 10);

if (date.equalsIgnoreCase(existingDirDate)) {
int dirSeqNo =
Integer.parseInt(dir.substring(baseDirLength + 11, baseDirLength + 10 + 3));

if (dirSeqNo > maxSeqNo) {
maxSeqNo = dirSeqNo;
}
}
}
}
}

String currSeq = "" + (maxSeqNo + 1);
if (currSeq.length() == 1) {
currSeq = "0" + currSeq;
}

newDir = baseDirectory + date;
new File(newDir).mkdir();
} catch (Exception e) {
e.printStackTrace();
}
}
return newDir;
}

如果我想每天创建一个新文件夹,我应该更改什么

最佳答案

您可以使用日志框架的功能来执行此操作。例如使用 Log4J's RollingFileAppender

您可以使用fileName参数创建新目录。来自 documentation :

fileName: The name of the file to write to. If the file, or any of its parent directories, do not exist, they will be created.

关于java - 如何每天创建新目录,并将其名称作为当前日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50928547/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com