fileKit

package
v2.1.30 Latest Latest
Warning

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

Go to latest
Published: Jul 12, 2023 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 (
	// PathSeparator 路径分隔符,Mac("/")
	PathSeparator          = string(os.PathSeparator)
	PathSeparatorRune rune = os.PathSeparator

	// PathListSeparator 路径列表分隔符,Mac(":")
	PathListSeparator          = string(os.PathListSeparator)
	PathListSeparatorRune rune = os.PathListSeparator
)

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 获取文件(或目录)信息
	Stat func(path string) (os.FileInfo, error) = gfile.Stat

	IsReadable func(path string) bool = gfile.IsReadable
	IsWritable func(path string) bool = gfile.IsWritable

	// 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

	// GetBaseName 获取 完整的文件名.
	/*
		e.g.
		/var/www/file.js -> file.js
		file.js          -> file.js
	*/
	GetBaseName func(path string) string = gfile.Basename

	// 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

	// Truncate 截断
	/*
		PS:
		(1) If the file is a symbolic link, it changes the size of the link's target.
		(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 (
	// Copy 复制文件(或目录)
	Copy func(src string, dst string) error = gfile.Copy

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

	// CopyDir 复制目录
	CopyDir func(src string, dst string) (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
)
View Source
var (
	// Open (只读模式)打开文件/目录.
	/*
		PS: flag == O_RDONLY.
	*/
	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 (
	ReadLines func(file string, callback func(line string) error) error = gfile.ReadLines

	ReadLinesBytes func(file string, callback func(bytes []byte) error) error = gfile.ReadLinesBytes
)

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) error

AssertNotExistOrIsDir

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

func AssertNotExistOrIsFile

func AssertNotExistOrIsFile(path string) error

AssertNotExistOrIsFile

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

func CloseOnExec

func CloseOnExec(f *os.File)

CloseOnExec makes sure closing the file on process forking.

参考: go-zero中 fs.CloseOnExec.

func Create added in v2.1.7

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

Create 创建文件(目录不行).

PS:
(1) flag == O_RDWR|O_CREATE|O_TRUNC
(2) 读写权限;
(3) path不存在,会创建;
(4) path存在 && 是文件,会清空该文件内容;
(5) path存在 && 是目录,会返回error.

func Detect added in v2.1.7

func Detect(in []byte) *mimetype.MIME

Detect

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

e.g.

mime := mimeTypeKit.Detect(nil)
fmt.Println(mime.ToDSN()) // "text/plain"

func DetectContentType added in v2.1.7

func DetectContentType(data []byte) string

DetectContentType 获取 ContentType(即MimeType).

PS: 读取前 512 个字节.

@return 保底 "application/octet-stream"

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

func DetectFile added in v2.1.7

func DetectFile(path string) (*mimetype.MIME, error)

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.ToDSN()) // application/x-ole-storage

mime, _ = mimeTypeKit.DetectFile("/Users/richelieu/Desktop/download.pdf")
fmt.Println(mime.ToDSN()) // application/pdf

func DetectReader added in v2.1.7

func DetectReader(r io.Reader) (*mimetype.MIME, error)

func EmptyDir

func EmptyDir(dirPath string) error

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

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

func GetFileMode added in v2.1.7

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 NewFile

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

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

func NewFileInAppendMode added in v2.1.9

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

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

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 ReadFile

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

ReadFile 读取文件的数据.

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

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

func ReadFileString added in v2.1.7

func ReadFileString(filePath string) (string, error)

func ReadLuaFile added in v2.1.7

func ReadLuaFile(path string) (string, error)

ReadLuaFile 按行读取 .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 WriteToFile

func WriteToFile(data []byte, filePath string) error

WriteToFile 将数据(字节流)写到文件中.

@param filePath 目标文件的路径(不存在的话,会创建一个新的文件;存在且是个文件的话,会覆盖掉旧的(并不会加到该文件的最后面))

Types

This section is empty.

Jump to

Keyboard shortcuts

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