如何遍历目录,根据文件时间排序

How to Iterate through directory, ordered based on the file time

Go 提供开箱即用的目录迭代功能,filepath.Walkpath/filepath 包中。

然而,filepath.Walk walks the file tree in lexical order。如何按照最后修改日期的顺序遍历文件树?谢谢

PS(接受答案后)我认为 Go filepath.Walk 函数应该为人们提供一种自己提供排序的方法,比如以下答案,其中接受 type ByModTime 是人们自己对文件进行排序所需要的。

我觉得,你应该自己实现,因为filepath.Walk不允许你设置顺序。

Walk method. It calls walk, which is relying on file names from readDirNames。所以基本上,您应该使用另一个 readDirNames 逻辑创建自己的 Walk 方法。

以下是按最后修改日期顺序获取文件的方法(注意,我忽略了错误):

package main

import (
    "fmt"
    "os"
    "sort"
)

type ByModTime []os.FileInfo

func (fis ByModTime) Len() int {
    return len(fis)
}

func (fis ByModTime) Swap(i, j int) {
    fis[i], fis[j] = fis[j], fis[i]
}

func (fis ByModTime) Less(i, j int) bool {
    return fis[i].ModTime().Before(fis[j].ModTime())
}

func main() {
    f, _ := os.Open("/")
    fis, _ := f.Readdir(-1)
    f.Close()
    sort.Sort(ByModTime(fis))

    for _, fi := range fis {
        fmt.Println(fi.Name())
    }
}