You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JSch框架获取含毫秒的远程文件时间戳?

解决JSch获取远程文件毫秒级时间戳的问题

你当前使用的getMtimeString()方法仅能返回秒级精度的时间,因为它内部是基于秒级时间戳生成格式化字符串的。要获取包含毫秒(甚至纳秒)的时间戳,需要直接从SftpATTRS中提取秒级时间和纳秒偏移量,再自行格式化。

实现步骤

  1. 从文件属性SftpATTRS中分别获取秒级时间戳(getMtime())和纳秒部分(getMtimeNano()),后者对应SFTP协议扩展的高精度时间属性。
  2. 使用Java 8+的时间API(Instant、DateTimeFormatter)将这两个值组合并格式化为带高精度的时间字符串。

修改后的代码示例

import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.LsEntry;
import com.jcraft.jsch.SftpATTRS;

// ... 已有的JSch会话初始化代码 ...

ChannelSftp channelSftp = (ChannelSftp) jschSession.openChannel("sftp");
channelSftp.connect();
List<LsEntry> files = channelSftp.ls("*.log");

// 定义包含纳秒的时间格式化器,时区对应IST(可按需调整)
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss.SSSSSSSSS zzz yyyy")
        .withZone(ZoneId.of("Asia/Kolkata"));

for (LsEntry entry : files) {
    SftpATTRS attrs = entry.getAttrs();
    long epochSeconds = attrs.getMtime();
    int nanos = attrs.getMtimeNano(); // 获取0-999999999的纳秒偏移量

    // 组合秒和纳秒生成高精度时间
    Instant fileInstant = Instant.ofEpochSecond(epochSeconds, nanos);
    String formattedTime = timeFormatter.format(fileInstant);

    log.info("File {}: {}", entry.getFilename(), formattedTime);
}

channelSftp.disconnect();

注意事项

  • 确保使用JSch 0.1.55及以上版本,旧版本没有getMtimeNano()方法,无法获取纳秒级精度。
  • 时区设置要与你的期望输出匹配,示例中Asia/Kolkata对应IST时区,可根据实际场景替换为其他时区ID(如UTC、Asia/Shanghai等)。
  • 如果远程服务器不支持SFTP的高精度时间扩展,getMtimeNano()会返回0,此时格式化后的时间会显示.000000000。

内容的提问来源于stack exchange,提问作者Jericho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 04:30:21