使用文件IO实现“每隔1秒向文件1.txt写入当前系统时间,行号递增
时间: 2024-10-29 12:13:37 浏览: 15
在Java中,你可以使用`FileWriter`、`BufferedWriter`以及定时任务`ScheduledExecutorService`来实现这个功能。下面是一个简单的示例:
```java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
public class TimeToFile {
private static final String FILE_NAME = "1.txt";
private static ScheduledExecutorService executorService;
private static int lineNumber = 1;
public static void main(String[] args) {
initExecutorService();
writeTimeToDisk();
}
private static void initExecutorService() {
executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(() -> writeTimeToDisk(), 0, 1, TimeUnit.SECONDS);
}
private static void writeTimeToDisk() {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_NAME, true))) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = dateFormat.format(new Date());
writer.write(currentTime + "\n" + lineNumber++);
writer.newLine(); // 结束这一行
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
}
}
}
```
这段代码首先初始化了一个单线程定时任务调度器,然后每过一秒就调用`writeTimeToDisk`方法。在这个方法里,它会获取当前的时间,并将其格式化为字符串,然后加上行号并写入到`1.txt`文件中,如果文件不存在,它会在追加模式下创建。每一行结束时会自动添加换行符。
阅读全文