有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Apache vfs:获取目录的最新更改文件(sftp)

我试图从位于sftp服务器上的目录中提取最新的文件。我现在的做法或多或少是:

public FileObject getLatestFile(String directory) throws FileSystemException {
    FileObject fo = fsManager.resolveFile(this.host+directory, fsOptions);
    FileObject latestFile = null;
    long max  = 0;
    fo.getContent().
    for (FileObject fob : fo.getChildren()){
        if (fob.getContent().getLastModifiedTime() > max) {
            max = fob.getContent().getLastModifiedTime();
            latestFile = fob;
        }
    }
    return latestFile;
}

这种方法的问题是,每次调用该方法时,我基本上都在下载给定目录中的每个文件

有没有更好的办法


共 (1) 个答案

  1. # 1 楼答案

    您没有下载内容

    如果查看源代码:

    /**
     * Returns the file's content.
     */
    public FileContent getContent() throws FileSystemException
    {
        synchronized (fs)
        {
            attach();
            if (content == null)
            {
                content = new DefaultFileContent(this, getFileContentInfoFactory());
            }
            return content;
        }
    }
    

    调用getContent只会返回一个对象实现,并获取诸如大小、修改日期之类的属性,基本上它是在探索远程文件夹时提取的(每个协议都不同,但例如,当您列出一个FTP文件夹时,您会获得所有文件属性)

    对于SFTP,您实际上称之为:

    protected long doGetLastModifiedTime() throws Exception
    {
        if (attrs == null
                || (attrs.getFlags() & SftpATTRS.SSH_FILEXFER_ATTR_ACMODTIME) == 0)
        {
            throw new FileSystemException(
                    "vfs.provider.sftp/unknown-modtime.error");
        }
        return attrs.getMTime() * 1000L;
    }
    

    我同意,命名是令人困惑的,它意味着在调用getContent时会检索内容,但实际上不会