设置/更改文件的ctime或"更改时间"属性

Eit*_*tan 7 java linux filemtime ext4 java.nio.file

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

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

我可以更改前两个时间戳字段,如下所示:

Files.setLastModifiedTime(pathToMyFile, myCustomTime);
Files.setAttribute(pathToMyFile, "basic:lastAccessTime", myCustomTime);
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢!

Eit*_*tan 13

我能够用两种不同的方法修改ctime:

  1. 更改内核以ctime匹配mtime
  2. 编写一个简单(但hacky)的shell脚本.

第一种方法:更改内核.

我只调整了几行.KERNEL_SRC/fs/attr.c 当mtime"明确定义"时,此修改更新ctime以匹配mtime.

有很多方法可以"明确定义"mtime,例如:

在Linux中:

touch -m --date="Wed Jun 12 14:00:00 IDT 2013" filename
Run Code Online (Sandbox Code Playgroud)

在Java中(使用Java 6或7,可能是其他人):

long newModificationTime = TIME_IN_MILLIS_SINCE_EPOCH;
File myFile = new File(myPath);
newmeta.setLastModified(newModificationTime);
Run Code Online (Sandbox Code Playgroud)

这里是变化KERNEL_SRC/fs/attr.cnotify_change函数:

    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)
    }
Run Code Online (Sandbox Code Playgroud)

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

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

第二种方法:简单(但是hacky)的shell脚本.

简要说明:1)将系统时间更改为目标时间2)对文件执行chmod,文件ctime现在反映目标时间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"
Run Code Online (Sandbox Code Playgroud)

运行如下:./ changectime.sh MYFILE

文件的ctime现在将反映文件中的时间.

当然,您可能不希望该文件具有777权限.确保在使用之前根据需要修改此脚本.

  • 需要更改脚本。now=$(date) 不(总是?)获取有效的日期格式进行设置。使用:now=$(日期+"%Y-%M-%d %T")。该脚本/方法很简洁,对我有用。 (2认同)