fileKit

package
v2.9.114 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 4, 2024 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const (

	// ModeAllReadWrite -rw-rw-rw-: 所有用户 有 读、写权限
	ModeAllReadWrite = os.FileMode(0666)

	// ModeAll -rwxrwxrwx: 所有用户 有 读、写、执行权限
	ModeAll = os.ModePerm
)

参考:https://blog.csdn.net/qq_39131177/article/details/85060694

!!!:0开头,即八进制.

r: 读权限(4) w: 写权限(2) x: 执行权限(1) -: 无权限(0)

View Source
const (
	PathSeparatorRune rune = os.PathSeparator

	// PathSeparator 路径分隔符,Mac("/")
	PathSeparator = string(os.PathSeparator)

	PathListSeparatorRune rune = os.PathListSeparator

	// PathListSeparator 路径列表分隔符,Mac(":")
	PathListSeparator = string(os.PathListSeparator)
)
View Source
const (
	// AllPerm 所有权限
	AllPerm = os.ModePerm

	// SafePerm 只有你自己有 写 权限
	SafePerm os.FileMode = 0644
)

Variables

View Source
var (
	Exists func(path string) bool = gfile.Exists
	IsFile func(path string) bool = gfile.IsFile
	IsDir  func(path string) bool = gfile.IsDir

	// Stat 获取文件(或目录)信息
	/*
		@param path 如果为""或不存在,将返回error(e.g."" => stat : no such file or directory)
	*/
	Stat func(path string) (os.FileInfo, error) = gfile.Stat

	// IsEmpty checks whether the given `path` is empty.
	/*
		If `path` is a folder, it checks if there's any file under it.
		If `path` is a file, it checks if the file size is zero.
		Note that it returns true if `path` does not exist.
	*/
	IsEmpty func(path string) bool = gfile.IsEmpty

	// GetFileName 获取 文件名.
	/*
		e.g.
		/var/www/file.js -> file.js
		file.js          -> file.js
	*/
	GetFileName func(path string) string = filepath.Base

	// GetName 获取 文件名的前缀.
	/*
		e.g.
		/var/www/file.js -> file
		file.js          -> file
	*/
	GetName func(path string) string = gfile.Name

	// GetExt 获取 文件名的后缀(带".")
	/*
		@return 可能为""

		e.g.
			println(fileKit.GetExt("main.go"))  // ".go"
			println(fileKit.GetExt("api.json")) // ".json"
			println(fileKit.GetExt(""))         // ""
			println(fileKit.GetExt("    "))     // ""
			println(fileKit.GetExt("empty"))    // ""
	*/
	GetExt func(path string) string = gfile.Ext

	// GetExtName 获取 后缀(不带".")
	/*
		@return 可能为""
		e.g.
			println(fileKit.GetExtName("main.go"))  // "go"
			println(fileKit.GetExtName("api.json")) // "json"
			println(fileKit.GetExtName(""))         // ""
			println(fileKit.GetExtName("    "))     // ""
			println(fileKit.GetExtName("empty"))    // ""
	*/
	GetExtName func(path string) string = gfile.ExtName
)
View Source
var (
	// GetModificationTime 获取文件(或目录)的修改时间
	GetModificationTime = gfile.MTime

	// GetModificationTimestamp 获取文件(或目录)的修改时间(单位: s)
	GetModificationTimestamp = gfile.MTimestamp

	// GetModificationTimestampMilli 获取文件(或目录)的修改时间(单位: ms)
	GetModificationTimestampMilli = gfile.MTimestampMilli
)
View Source
var (
	// Chmod 使用指定的权限,更改指定路径的文件权限.
	Chmod func(path string, mode os.FileMode) (err error) = gfile.Chmod

	// CutAndPaste 剪贴.
	CutAndPaste func(src string, dst string) (err error) = gfile.Move

	// Move 移动.
	Move func(src string, dst string) (err error) = gfile.Move

	// Rename 重命名.
	Rename func(src string, dst string) (err error) = gfile.Move

	// Remove 删除文件(或目录).
	/*
		PS: 如果是目录且内部有文件或目录,也会一并删除.
	*/
	Remove func(path string) (err error) = gfile.Remove

	// Delete 删除文件(或目录).
	Delete func(path string) (err error) = Remove

	// Truncate 裁剪文件为指定大小.
	/*
		PS:
		(1) 如果给定文件路径是软链,将会修改源文件;
		(2) If there is an error, it will be of type *PathError.

		@param size 如果为0,则清空文件内容
	*/
	Truncate func(path string, size int) (err error) = gfile.Truncate
)
View Source
var (
	ReadLines func(file string, callback func(line string) error) error = gfile.ReadLines

	ReadLinesBytes func(file string, callback func(bytes []byte) error) error = gfile.ReadLinesBytes
)
View Source
var (
	// Copy 复制文件(或目录)
	/*
		PS: 可以设置权限.
	*/
	Copy func(src string, dst string, option ...gfile.CopyOption) error = gfile.Copy

	// CopyFile 复制文件
	CopyFile func(src, dst string, option ...gfile.CopyOption) (err error) = gfile.CopyFile

	// CopyDir 复制目录
	CopyDir func(src string, dst string, option ...gfile.CopyOption) (err error) = gfile.CopyDir
)
View Source
var (
	// CreateSoftLink 创建软链接
	/*
	   Golang 之 文件硬连接 与 软连接: https://blog.csdn.net/icebergliu1234/article/details/109208030

	   @param src	源文件
	   @param dest	生成链接的位置
	*/
	CreateSoftLink func(oldname, newname string) error = os.Symlink

	// CreateHardLink 创建软链接
	/*
	   Golang 之 文件硬连接 与 软连接: https://blog.csdn.net/icebergliu1234/article/details/109208030

	   @param src	源文件
	   @param dest	生成链接的位置
	*/
	CreateHardLink func(oldname, newname string) error = os.Link

	// IsLink 判断文件是否是符号链接.
	IsLink func(path string) bool = fileutil.IsLink
)
View Source
var (
	// Open (只读模式)打开文件/目录.
	/*
		!!!: 只读权限 打开.
	*/
	Open func(path string) (*os.File, error) = gfile.Open

	// OpenFile (以指定 flag 和 perm)打开文件/目录.
	/*
		@param flag 详见".info"
		@param perm	(1) 可以参考 "fileKit/consts.go"
					(2) e.g.0666 || os.ModePerm ...
	*/
	OpenFile func(path string, flag int, perm os.FileMode) (*os.File, error) = gfile.OpenFile
)
View Source
var (
	// IsReadable 是否有 读 权限?
	/*
		@param path 文件(或目录)的路径
		@return 传参path不存在的话,将返回false

		e.g.
			("") => false
	*/
	IsReadable func(path string) bool = gfile.IsReadable

	// IsWritable 是否有 写 权限?
	/*
		@param path 文件(或目录)的路径
		@return 传参path不存在的话,将返回false

		e.g.
			("") => false
	*/
	IsWritable func(path string) bool = gfile.IsWritable
)
View Source
var CloseOnExec func(f *os.File) = fs.CloseOnExec

CloseOnExec makes sure closing the file on process forking.

参考: go-zero中 fs.CloseOnExec.

View Source
var Detect func(in []byte) *mimetype.MIME = mimetype.Detect

Detect

PS: (1) mimetype库: 基于magic数的用于媒体类型和文件扩展名检测的快速的 Go 库,支持 170+ 格式. (2) 读取前 3072 个字节.

View Source
var DetectContentType func(data []byte) string = http.DetectContentType

DetectContentType 获取 ContentType(即MimeType).

PS: 读取前 512 个字节.

@return 保底 "application/octet-stream"

e.g. ([]byte(nil)) => "text/plain; charset=utf-8" ([]byte{}) => "text/plain; charset=utf-8"

View Source
var DetectFile func(path string) (*mimetype.MIME, error) = mimetype.DetectFile

DetectFile

PS: 默认limit为: 3KB(3072).

TODO: https://github.com/gabriel-vasile/mimetype

mimetype.SetLimit(1024*1024) // Set limit to 1MB.
// or
mimetype.SetLimit(0) // No limit, whole file content used.
mimetype.DetectFile("file.doc")

e.g.

mime, _ := mimeTypeKit.DetectFile("/Users/richelieu/Desktop/未命名.wps")
fmt.Println(mime.String()) // application/x-ole-storage

mime, _ = mimeTypeKit.DetectFile("/Users/richelieu/Desktop/download.pdf")
fmt.Println(mime.String()) // application/pdf
View Source
var DetectReader func(r io.Reader) (*mimetype.MIME, error) = mimetype.DetectReader
View Source
var ReadDir func(name string) ([]os.DirEntry, error) = os.ReadDir

ReadDir 获取指定目录下的文件或目录(另一种遍历目录的方法).

PS: (1) 不包含子目录下的文件(|| 目录) (2) 第一个返回值是按照 文件名从小到大 排序的(目录 && 文件)

@param name 目录路径

(1) 如果为"" ,将返回error
(2) 可以为"."

Functions

func AssertExist

func AssertExist(path string) error

AssertExist

@param path 文件(或目录)的路径

func AssertExistAndIsDir

func AssertExistAndIsDir(path string) error

AssertExistAndIsDir

@return 如果path存在且是个目录,返回nil

func AssertExistAndIsFile

func AssertExistAndIsFile(path string) error

AssertExistAndIsFile

@return 如果path存在且是个文件,返回nil

func AssertNotExistOrIsDir

func AssertNotExistOrIsDir(path string, mkdirArgs ...bool) error

AssertNotExistOrIsDir

通过的情况: 不存在 || 存在但是个目录 不通过的情况: 存在但是个文件

@param mkdirArgs (1) true: path不存在的话,为其创建目录(可多级)

(2) 默认: true

func AssertNotExistOrIsFile

func AssertNotExistOrIsFile(path string, mkdirArgs ...bool) error

AssertNotExistOrIsFile

通过的情况: 不存在 || 存在但是个文件 不通过的情况: 存在但是个目录

@param mkdirArgs (1) true: path不存在的话,为其创建父目录(可多级)

(2) 默认: true

func AssertReadable

func AssertReadable(path string) error

func AssertReadableAndWritable

func AssertReadableAndWritable(path string) error

AssertReadableAndWritable

前提: path 非blank && 存在.

func AssertWritable

func AssertWritable(path string) error

func Create

func Create(filePath string) (*os.File, error)

Create 创建文件(读写权限、文件不存在就创建、打开并清空文件).

TODO: perm 权限可自定义,看后续 gfile 后不会完善.

@param filePath 会尝试为其创建父目录

PS: (1) 读写权限(0644); (2) path不存在,会创建; (3) path存在 && 是文件,会 截断 该文件内容; (4) path存在 && 是目录,会返回error.

func CreateInAppendMode

func CreateInAppendMode(filePath string) (*os.File, error)

CreateInAppendMode 创建文件(读写权限、文件不存在就创建、追加模式).

TODO: perm 权限可自定义,看后续 gfile 后不会完善.

func EmptyDir

func EmptyDir(dirPath string) error

EmptyDir 清空目录:删掉目录中的文件和子目录(递归),但该目录本身不会被删掉.

@param dirPath 可以不存在(此时将返回nil)

func GetFileMode

func GetFileMode(path string) (os.FileMode, error)

GetFileMode get mode and permission bits of file/directory

func GetSize

func GetSize(path string) (int64, error)

GetSize 获取文件(或目录)的大小.

func IsHidden

func IsHidden(path string) (bool, error)

IsHidden 文件(或目录)是否隐藏?

如何在 Go 中检测文件夹中的隐藏文件 - 跨平台方法

https://www.likecs.com/ask-919454.html#sc=1368.5

流程: (1) 获取文件名(以防传参为路径) (2) 判断文件名是否以"."开头

PS: (1) 传参path 对应的文件或目录必须存在,否则返回error.

@param 文件(或目录)的 path 或 name

func MkDirs

func MkDirs(dirPaths ...string) error

MkDirs 为目录路径,创建(一级或多级)目录.

PS: (1) 如果目录已经存在,将返回nil; (2) 如果 传参dirPath 对应的是个已存在的文件,将返回error("mkdir {xxx}: not a directory").

@param dirPaths 目录路径s(相对路径 || 绝对路径)

e.g.

("i:/test/test.exe") 	=> 	路径没问题且目录不存在的情况下,会在i盘创建"test"、"test.exe"两个目录
("i:/test1/test2/")		=>	路径没问题且目录不存在的情况下,会在i盘创建"test1"、"test2"两个目录

e.g.1 Mac

("")					=>	nil(什么都不会做)
("/")					=>	nil(什么都不会做)
(".")					=>	nil(什么都不会做)
("./")					=>	nil(什么都不会做)

func MkParentDirs

func MkParentDirs(paths ...string) error

MkParentDirs 为父路径,创建(一级或多级)目录.

@param filePaths (文件 || 目录)路径s(相对路径 || 绝对路径)

e.g.

("")	=> nil
(".")	=> nil

func NewTemporaryFile

func NewTemporaryFile(dirPath, pattern string) (*os.File, error)

NewTemporaryFile 在指定目录下,生成临时文件.

@param dirPath 如果为"",临时文件将生成在 系统临时目录 内;如果为".",临时文件将生成在 当前目录 内.

e.g. pattern: "tempfile_test" => 临时文件的文件名: "tempfile_test2594316144" pattern: "tempfile_test*" => 临时文件的文件名: "tempfile_test827818253" pattern: "tempfile_test*.xyz" => 临时文件的文件名: "tempfile_test3617672388.xyz"

func ReadCsvFile added in v2.8.163

func ReadCsvFile(filePath string) ([][]string, error)

ReadCsvFile 读取csv文件内容到切片.

func ReadFile

func ReadFile(filePath string) ([]byte, error)

ReadFile 读取文件的数据.

PS: (1) ioutil.ReadFile() 比 ioutil.ReadAll() 性能好,特别是大文件; (2) 编码必须为"UTF-8"!!! (3) 读取大文件也很快.

@param path 文件的路径(不能是目录的路径)

func ReadFileByLine

func ReadFileByLine(filePath string, f func(scan *bufio.Scanner)) error

ReadFileByLine

@param f 调用scan.Bytes() || scan.Text()

func ReadFileToString

func ReadFileToString(filePath string) (string, error)

func ReadLuaFileToString

func ReadLuaFileToString(filePath string) (string, error)

ReadLuaFileToString 按行读取 .lua文件 的内容.

@param path .lua文件的路径

func SetModificationTime

func SetModificationTime(path string, t time.Time) error

SetModificationTime 修改文件(或目录)的修改时间

PS: (1) 也会同时修改文件(或目录)的访问时间; (2) 修改目录的修改时间,将不会影响该目录下的文件或目录; (3) 传参t可以晚于当前时间.

@param path 传参""将返回error(chtimes : The system cannot find the path specified.)

func WriteCsvFile added in v2.8.165

func WriteCsvFile(filePath string, records [][]string, append bool) error

WriteCsvFile 向csv文件写入内容.

func WriteStringToFile

func WriteStringToFile(filePath string, content string, append bool) error

WriteStringToFile 将数据(字符串)写到文件中.

@param filePath 目标文件的路径, (1)不存在的话,会创建一个新的文件;

(2) 存在且是个文件的话,由 传参append 决定.

func WriteToFile

func WriteToFile(filePath string, data []byte, perm os.FileMode) error

WriteToFile 将数据([]byte, 字节流)写到文件中.

@param filePath 目标文件的路径

(1) 不存在的话,会创建一个新的文件;
(2) 存在且是个文件的话,会 "覆盖" 掉旧的(并不会加到该文件的最后面).

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL