Golang 如何检查文件大小和上次修改时间
In Golang语言中, os 模块提供了访问本地操作系统功能的能力。在 os 包中, Stat()函数 被用于检查文件大小和上次修改时间 。 该方法给出描述文件的 FileInfo 结构和类型为*PathError的错误。
// FileInfo描述文件并被stat返回
type FileInfo interface {
Name() string
Size() int64
Mode() FileMode
ModTime() time.Time()
IsDir() bool
Sys() any
}
下面FileInfo的方法被用于获取文件名、大小和最后修改时间:
Name(): 返回文件名。
Size(): 对于常规文件,返回字节数;对于其他文件,返回系统相关值。
ModTime(): 返回文件的最后修改时间。
例子1: 下面是一个用于检查文件的大小和修改时间的Golang程序。
// Golang program to check the size and
// modified time of a file
package main
// Importing the required packages
import (
"fmt"
"log"
"os"
)
func main() {
// Get the fileinfo
fileInfo, err := os.Stat("cpnew.txt")
// Checks for the error
if err != nil {
log.Fatal(err)
}
// Gives the modification time
modificationTime := fileInfo.ModTime()
fmt.Println("Name of the file:", fileInfo.Name(),
" Last modified time of the file:",
modificationTime)
// Gives the size of the file in bytes
fileSize := fileInfo.Size()
fmt.Println("Size of the file:", fileSize)
}
输出:
例子2: 下面是一个用于检查文件是否存在的Golang程序。
图1
// Golang程序检查文件是否存在
package main
// 导入必需的包
import (
"errors"
"fmt"
"os"
)
func main() {
_, err := os.Stat("cpnew.txt")
// Is函数用于判断是否存在目标错误
// 这里目标错误是os.ErrNotExist
// 当err等于ErrNotExist时,函数返回true
// 这意味着目录中不存在该文件
if errors.Is(err, os.ErrNotExist) {
fmt.Println("文件不存在")
} else
{
fmt.Println("文件存在")
}
_, err1 := os.Stat("test.txt")
if errors.Is(err1, os.ErrNotExist) {
fmt.Println("文件不存在")
} else
{
fmt.Println("文件存在")
}
}
输出: