gpt4 book ai didi

java - 滚动文件实现

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

我一直很好奇滚动文件是如何在日志中实现的。

甚至如何开始创建任何语言的文件编写类以确保不超过文件大小。

我能想到的唯一可能的解决方案是:

write method:
size = file size + size of string to write
if(size > limit)
close the file writer
open file reader
read the file
close file reader
open file writer (clears the whole file)
remove the size from the beginning to accommodate for new string to write
write the new truncated string
write the string we received

这似乎是一个糟糕的实现,但我想不出更好的方法。

具体来说,我希望看到 java 中的解决方案。

编辑:通过从开头删除大小,假设我有 20 字节的字符串(这是限制),我想写另一个 3 字节的字符串,因此我从开头删除 3 个字节,剩下的是结尾17 个字节,通过附加新字符串我有 20 个字节。

最佳答案

因为你的问题让我深入研究,这里有一个来自 logback 日志框架的例子。 RollingfileAppender#rollover() 方法如下所示:

public void rollover() {
synchronized (lock) {
// Note: This method needs to be synchronized because it needs exclusive
// access while it closes and then re-opens the target file.
//
// make sure to close the hereto active log file! Renaming under windows
// does not work for open files
this.closeOutputStream();

try {
rollingPolicy.rollover(); // this actually does the renaming of files
} catch (RolloverFailure rf) {
addWarn("RolloverFailure occurred. Deferring roll-over.");
// we failed to roll-over, let us not truncate and risk data loss
this.append = true;
}

try {
// update the currentlyActiveFile
currentlyActiveFile = new File(rollingPolicy.getActiveFileName());

// This will also close the file. This is OK since multiple
// close operations are safe.
// COMMENT MINE this also sets the new OutputStream for the new file
this.openFile(rollingPolicy.getActiveFileName());
} catch (IOException e) {
addError("setFile(" + fileName + ", false) call failed.", e);
}
}
}

如您所见,逻辑与您发布的内容非常相似。它们关闭当前的 OutputStream,执行翻转,然后打开一个新的 (openFile())。显然,这一切都是在 synchronized block 中完成的,因为许多线程都在使用记录器,但一次只应发生一次翻转。

RollingPolicy 是关于如何执行翻转的策略,TriggeringPolicy 是何时执行翻转的策略。使用 logback,您通常将这些策略基于文件大小或时间。

关于java - 滚动文件实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16739035/

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