如何检查路径上的目录是否为空?
How to check if directory on path is empty?
如果文件夹为空,如何检查Go?我可以这样检查:
files, err := ioutil.ReadDir(*folderName)
if err != nil {
return nil, err
}
// here check len of files
但我觉得应该有更优雅的解决方案。
目录是否为空不会作为名称、创建时间或大小(对于文件)等属性存储在 file-system 级别中。
话虽如此,您不能仅从 os.FileInfo
中获取此信息。最简单的方法是查询目录的children(内容)
ioutil.ReadDir()
is quite a bad choice as that first reads all the contents of the specified directory and then sorts them by name, and then returns the slice. The fastest way is as Dave C mentioned: query the children of the directory using File.Readdir()
or (preferably) File.Readdirnames()
.
File.Readdir()
和File.Readdirnames()
都带有一个参数,用于限制返回值的数量。只查询1个child就够了。由于 Readdirnames()
returns 仅命名,因此速度更快,因为不需要进一步调用来获取(和构造)FileInfo
结构。
请注意,如果目录为空,io.EOF
将作为错误返回(而不是空或 nil
切片),因此我们甚至不需要返回的名称切片。
最终代码可能如下所示:
func IsEmpty(name string) (bool, error) {
f, err := os.Open(name)
if err != nil {
return false, err
}
defer f.Close()
_, err = f.Readdirnames(1) // Or f.Readdir(1)
if err == io.EOF {
return true, nil
}
return false, err // Either not empty or error, suits both cases
}
如果文件夹为空,如何检查Go?我可以这样检查:
files, err := ioutil.ReadDir(*folderName)
if err != nil {
return nil, err
}
// here check len of files
但我觉得应该有更优雅的解决方案。
目录是否为空不会作为名称、创建时间或大小(对于文件)等属性存储在 file-system 级别中。
话虽如此,您不能仅从 os.FileInfo
中获取此信息。最简单的方法是查询目录的children(内容)
ioutil.ReadDir()
is quite a bad choice as that first reads all the contents of the specified directory and then sorts them by name, and then returns the slice. The fastest way is as Dave C mentioned: query the children of the directory using File.Readdir()
or (preferably) File.Readdirnames()
.
File.Readdir()
和File.Readdirnames()
都带有一个参数,用于限制返回值的数量。只查询1个child就够了。由于 Readdirnames()
returns 仅命名,因此速度更快,因为不需要进一步调用来获取(和构造)FileInfo
结构。
请注意,如果目录为空,io.EOF
将作为错误返回(而不是空或 nil
切片),因此我们甚至不需要返回的名称切片。
最终代码可能如下所示:
func IsEmpty(name string) (bool, error) {
f, err := os.Open(name)
if err != nil {
return false, err
}
defer f.Close()
_, err = f.Readdirnames(1) // Or f.Readdir(1)
if err == io.EOF {
return true, nil
}
return false, err // Either not empty or error, suits both cases
}