java - 设置/更改文件的 ctime 或 "Change time"属性

标签 java linux ext4 filemtime java.nio.file

我希望使用 java.nio.Files 类更改 Java 文件的时间戳元数据。

我想更改所有 3 个 Linux/ext4 时间戳(最后修改、访问和更改)。

我可以按如下方式更改前两个时间戳字段:

Files.setLastModifiedTime(pathToMyFile, myCustomTime);
Files.setAttribute(pathToMyFile, "basic:lastAccessTime", myCustomTime);

但是,我无法修改文件的上次更改: 时间。此外,令人担忧的是 documentation 中没有提到更改时间戳。 .最接近的可用属性是 creationTime,我尝试过但没有成功。

关于如何根据 Java 中的自定义时间戳修改文件的 Change: 元数据有什么想法吗?

谢谢!

最佳答案

我可以用两种不同的方法修改 ctime:

  1. 更改内核,使 ctimemtime 匹配
  2. 正在编写一个简单(但很老套)的 shell 脚本。

第一种方法:更改内核。

我只调整了 KERNEL_SRC/fs/attr.c 中的几行代码,每当 mtime 被“显式定义”时,此修改都会更新 ctime 以匹配 mtime。

“显式定义”mtime的方式有很多种,例如:

在 Linux 中:

touch -m --date="Wed Jun 12 14:00:00 IDT 2013" filename

在 Java 中(使用 Java 6 或 7,可能还有其他的):

long newModificationTime = TIME_IN_MILLIS_SINCE_EPOCH;
File myFile = new File(myPath);
newmeta.setLastModified(newModificationTime);

这是 notify_change 函数中对 KERNEL_SRC/fs/attr.c 的更改:

    now = current_fs_time(inode->i_sb);

    //attr->ia_ctime = now;  (1) Comment this out
    if (!(ia_valid & ATTR_ATIME_SET))
        attr->ia_atime = now;
    if (!(ia_valid & ATTR_MTIME_SET)) {
        attr->ia_mtime = now;
    }
    else { //mtime is modified to a specific time. (2) Add these lines
        attr->ia_ctime = attr->ia_mtime; //Sets the ctime
        attr->ia_atime = attr->ia_mtime; //Sets the atime (optional)
    }

(1) 此行未注释,将在文件更改时将 ctime 更新为当前时钟时间。我们不希望这样,因为我们想自己设置 ctime。因此,我们将这一行注释掉。 (这不是强制性的)

(2) 这确实是解决方案的关键。 notify_change 函数在文件更改后执行,需要更新时间元数据。如果未指定 mtime,则将 mtime 设置为当前时间。否则,如果 mtime 设置为特定值,我们也将 ctime 和 atime 设置为该值。

第二种方法:简单(但很老套)的 shell 脚本。

简要说明:

  1. 将系统时间更改为您的目标时间
  2. 对文件执行 chmod,文件 ctime 现在反射(reflect)目标时间
  3. 恢复系统时间。

changectime.sh

#!/bin/sh
now=$(date)
echo $now
sudo date --set="Sat May 11 06:00:00 IDT 2013"
chmod 777 $1
sudo date --set="$now"

按如下方式运行: ./changectime.sh 我的文件

文件的 ctime 现在将反射(reflect)文件中的时间。

当然,您可能不想要具有 777 权限的文件。确保在使用前根据您的需要修改此脚本。

关于java - 设置/更改文件的 ctime 或 "Change time"属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16126992/

相关文章:

java - 是否可以在没有连接设备的情况下写入串行端口?

java - 文件对象转字节数组-android开发

Java 进程优先于其他 Windows 进程

java - HttpUrlConnection 和 setReadTimeout() 方法

filesystems - 使用 fdisk 更改分区会显示类似 "partition#x contains ext4-signature"的警告

java - 在 Java 中将日志写入 SSD 的最快方法是什么?

java - 为什么 Java 无法在我的 Ubuntu 桌面上创建此文件?

java - 在服务器上运行 IRC-Bot?

linux - 在 Windows 10 上使用 bash 定位我的串行端口时遇到问题

linux - 如何摆脱 'GLIBCXX_3.4.9 not found error' ?