gpt4 book ai didi

Java:每隔几秒创建一次文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:16:15 25 4
gpt4 key购买 nike

我正在使用 ScheduledThreadPoolExecutor 每 fileIntervalInSeconds 秒创建一个文件:

executorService = new ScheduledThreadPoolExecutor(1);
executorService.scheduleAtFixedRate(new Runnable()
{
@Override
public void run()
{
File file = new File(fileName);
if (file.exists())
{
Log.debug("creating new file");
openFileWriter(file);
}

}
}, fileIntervalInSeconds, fileIntervalInSeconds, TimeUnit.SECONDS);
}
private void openFileWriter() throws FileSystemNotificationException
{

// 1 - close exist writer
writer.close();
// 2 - rename to backup file name
...
// 3 - create new file
FileWriter writerFile = new FileWriter(fileName, true);
writer = new PrintWriter(writerFile);

}

而且我一直在向文件写入警报消息:

private synchronized void writeLine(String line) throws InterruptedException
{
writer.println(line);
}

我的问题是:

  1. 我如何确保在 writer 未关闭时我正在使用它? (writer.close())
  2. 如何在开始写入之前等待 ScheduledThreadPoolExecutor 完成创建文件

最佳答案

在写入文件之前如何检查文件是否存在。无需后台线程或同步

private synchronized void writeLine(String line) {
if (!file.exists())
reopenWritingFile();
writer.println(line);
}

关于Java:每隔几秒创建一次文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19908270/

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