【问题标题】:Write to a specific file every 10 secs每 10 秒写入特定文件
【发布时间】:2020-12-30 05:20:35
【问题描述】:

我正在尝试使用 spring boot 的 @Scheduled 每 10 秒将当前系统时间打印到特定的文本文件。

我已经设法创建了如下内容:

@Scheduled(fixedRate = 10000) // 10 seconds
public void writeToMyFile() {
    try {
        BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\temp\\envVarFile.txt", true));
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
        try {
            writer.append(formatter.format(System.currentTimeMillis()));
        }
        catch(IOException e){
            e.printStackTrace()
        }
        writer.close(); 
    }
    catch(Exception e) {
        e.printStackTrace()
    }
}

我不知道我是在创建文件新文件还是在最初创建的“envVarFile”文件上写入。

如果有人可以提供帮助,我会很高兴。

!重要!: @Rakesh 的解决方案有效,但在 envVarFile.txt 存在于 C 内的 temp 目录下的情况下应用于代码:

【问题讨论】:

  • 环境变量不会改变。为什么要反复写?
  • @chrylis-cautiouslyoptimistic- 它不需要是环境变量,它可以是任何不是我主要关心的任意文本。
  • 根据写入新文件或现有文件的问题,下面提供的答案标记为无用。请确认原因或更详细地解释问题
  • @Rakesh 我目前正在尝试您的解决方案,我不是将答案标记为无用的人。
  • 感谢您的友好回复。如果您遇到任何问题,请尝试让我知道。我们正在使用几个地方@Scheduled,因为我们有几个批处理作业。

标签: java spring-boot file-io bufferedwriter spring-scheduled


【解决方案1】:

请在下方使用

  File yourfile = new File(filename);
        if(yourfile.exists()){
            writer = Files.newBufferedWriter(Paths.get(filename), StandardCharsets.UTF_8,StandardOpenOption.APPEND);
        }else{
            writer = Files.newBufferedWriter(Paths.get(filename), StandardCharsets.UTF_8,StandardOpenOption.CREATE_NEW);
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    相关资源
    最近更新 更多