java往文件中写入时间
时间: 2023-09-15 21:02:09 浏览: 148
在Java中,我们可以使用java.time包中的LocalDateTime类来获取当前时间,并将其写入文件。下面是一个示例代码:
```java
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class WriteTimeToFile {
public static void main(String[] args) {
// 获取当前时间
LocalDateTime currentTime = LocalDateTime.now();
// 格式化时间字符串
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedTime = currentTime.format(formatter);
// 将时间写入文件
try (FileWriter writer = new FileWriter("time.txt")) {
writer.write(formattedTime);
} catch (IOException e) {
System.out.println("写入文件时发生错误:" + e.getMessage());
}
}
}
```
以上代码首先通过LocalDateTime类获取当前时间,并使用DateTimeFormatter对时间进行格式化,得到一个格式化的时间字符串。然后,我们使用FileWriter将时间字符串写入到名为time.txt的文件中。
需要注意的是,在处理文件操作时,我们通常使用try-with-resources语句,以确保文件在使用完毕后能够被正确关闭。在上述代码中,使用了try-with-resources来自动关闭FileWriter对象。
执行以上代码后,会在当前工作目录(即代码所在的目录)中生成一个名为time.txt的文件,其中包含了当前时间的格式化字符串。