背景
很多时候,我们修改对指定的文件进行修改其的创建时间、修改时间、最后访问时间,以便达到自己的目的。
代码操作
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ModifyFileTimes {
public static void main(String[] args) {
// Path filePath = Paths.get("path/to/your/file.txt"); // 替换为你的文件路径
Path filePath = Paths.get("D:\\测试\\文件名.后缀名"); // 替换为你的文件路径
try {
//时间格式化工具类
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse("2025-01-02 15:00:18");
// 设置文件的创建时间
FileTime newCreationTime = FileTime.fromMillis(date.getTime());
Files.setAttribute(filePath, "creationTime", newCreationTime);//这种方式,修改完底层代码会覆盖掉原始文件,以下类同
// 设置文件的最后修改时间
FileTime newModifyTime = FileTime.fromMillis(date.getTime());
Files.setLastModifiedTime(filePath, newModifyTime);
// 设置文件的最后访问时间
FileTime newAccessTime = FileTime.fromMillis(date.getTime());
// Files.setLastAccessTime(filePath, newAccessTime);
//Java8中使用setAttribute方法,设置最后访问时间
Files.setAttribute(filePath, "lastAccessTime", newAccessTime);
System.out.println("文件时间已修改。");
//最后,通过文件管理器查看文件时间是否已更改。
} catch (IOException e) {
e.printStackTrace();
System.out.println("修改文件时间失败。");
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
效果展示
修改前:

修改后:


680

被折叠的 条评论
为什么被折叠?



