You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 25 Next »

基本介绍

gfile模块是对文件操作的进一步封装,提供了常用的,简易的API来操作底层文件,隐藏了复杂的底层实现细节。

使用方式

import "github.com/gogf/gf/v2/os/gfile"

接口文档

https://pkg.go.dev/github.com/gogf/gf/v2/os/gfile


内容缓存

GetContentsWithCache

  • 说明:带缓存获取文件内容,可设置缓存超时,文件发生变化自动清除缓存
  • 示例:

    func ExampleGetContentsWithCache() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_cache")
    		tempFile = gfile.Join(tempDir, fileName)
    	)
    
    	// write contents
    	gfile.PutContents(tempFile, "goframe example content")
    
    	// It reads the file content with cache duration of one minute,
    	// which means it reads from cache after then without any IO operations within on minute.
    	fmt.Println(gfile.GetContentsWithCache(tempFile, time.Minute))
    
    	// write new contents will clear its cache
    	gfile.PutContents(tempFile, "new goframe example content")
    
    	// There's some delay for cache clearing after file content change.
    	time.Sleep(time.Second * 1)
    
    	// read contents
    	fmt.Println(gfile.GetContentsWithCache(tempFile))
    
    	// May Output:
    	// goframe example content
    	// new goframe example content
    }

内容管理

GetContents

  • 说明:指定路径文件字符串内容读取
  • 示例:

    func ExampleGetContents() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_content")
    		tempFile = gfile.Join(tempDir, fileName)
    	)
    
    	// write contents
    	gfile.PutContents(tempFile, "goframe example content")
    
    	// It reads and returns the file content as string.
    	// It returns empty string if it fails reading, for example, with permission or IO error.
    	fmt.Println(gfile.GetContents(tempFile))
    
    	// Output:
    	// goframe example content
    }

GetBytes

  • 说明:指定路径文件字节内容读取
  • 示例:

    func ExampleGetBytes() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_content")
    		tempFile = gfile.Join(tempDir, fileName)
    	)
    
    	// write contents
    	gfile.PutContents(tempFile, "goframe example content")
    
    	// It reads and returns the file content as []byte.
    	// It returns nil if it fails reading, for example, with permission or IO error.
    	fmt.Println(gfile.GetBytes(tempFile))
    
    	// Output:
    	// [103 111 102 114 97 109 101 32 101 120 97 109 112 108 101 32 99 111 110 116 101 110 116]
    }

PutContents

  • 说明:设置指定路径文件字符串内容
  • 示例:

    func ExamplePutContents() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_content")
    		tempFile = gfile.Join(tempDir, fileName)
    	)
    
    	// It creates and puts content string into specifies file path.
    	// It automatically creates directory recursively if it does not exist.
    	gfile.PutContents(tempFile, "goframe example content")
    
    	// read contents
    	fmt.Println(gfile.GetContents(tempFile))
    
    	// Output:
    	// goframe example content
    }

PutBytes

  • 说明:设置指定路径文件字节内容
  • 示例:

    func ExamplePutBytes() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_content")
    		tempFile = gfile.Join(tempDir, fileName)
    	)
    
    	// write contents
    	gfile.PutBytes(tempFile, []byte("goframe example content"))
    
    	// read contents
    	fmt.Println(gfile.GetContents(tempFile))
    
    	// Output:
    	// goframe example content
    }

PutContentsAppend

  • 说明:添加字符串内容到指定路径文件
  • 示例:

    func ExamplePutContentsAppend() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_content")
    		tempFile = gfile.Join(tempDir, fileName)
    	)
    
    	// write contents
    	gfile.PutContents(tempFile, "goframe example content")
    
    	// read contents
    	fmt.Println(gfile.GetContents(tempFile))
    
    	// It creates and append content string into specifies file path.
    	// It automatically creates directory recursively if it does not exist.
    	gfile.PutContentsAppend(tempFile, " append content")
    
    	// read contents
    	fmt.Println(gfile.GetContents(tempFile))
    
    	// Output:
    	// goframe example content
    	// goframe example content append content
    }

PutBytesAppend

  • 说明:添加字节内容到指定路径文件
  • 示例:

    func ExamplePutBytesAppend() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_content")
    		tempFile = gfile.Join(tempDir, fileName)
    	)
    
    	// write contents
    	gfile.PutContents(tempFile, "goframe example content")
    
    	// read contents
    	fmt.Println(gfile.GetContents(tempFile))
    
    	// write contents
    	gfile.PutBytesAppend(tempFile, []byte(" append"))
    
    	// read contents
    	fmt.Println(gfile.GetContents(tempFile))
    
    	// Output:
    	// goframe example content
    	// goframe example content append
    }

GetNextCharOffsetByPath

  • 说明:从某个偏移量开始,获取文件中指定字符所在下标
  • 示例:

    func ExampleGetNextCharOffsetByPath() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_content")
    		tempFile = gfile.Join(tempDir, fileName)
    	)
    
    	// write contents
    	gfile.PutContents(tempFile, "goframe example content")
    
    	// read contents
    	index := gfile.GetNextCharOffsetByPath(tempFile, 'f', 0)
    	fmt.Println(index)
    
    	// Output:
    	// 2
    }

GetBytesTilCharByPath

  • 说明:以某个字符定位截取指定长度的文件内容以字节形式返回
  • 示例:

    func ExampleGetBytesTilCharByPath() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_content")
    		tempFile = gfile.Join(tempDir, fileName)
    	)
    
    	// write contents
    	gfile.PutContents(tempFile, "goframe example content")
    
    	// read contents
    	fmt.Println(gfile.GetBytesTilCharByPath(tempFile, 'f', 0))
    
    	// Output:
    	// [103 111 102] 2
    }

GetBytesByTwoOffsetsByPath

  • 说明:用两个偏移量截取指定文件的内容以字节形式返回
  • 示例:

    func ExampleGetBytesByTwoOffsetsByPath() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_content")
    		tempFile = gfile.Join(tempDir, fileName)
    	)
    
    	// write contents
    	gfile.PutContents(tempFile, "goframe example content")
    
    	// read contents
    	fmt.Println(gfile.GetBytesByTwoOffsetsByPath(tempFile, 0, 7))
    
    	// Output:
    	// [103 111 102 114 97 109 101]
    }

ReadLines

  • 说明:以字符串形式逐行读取文件内容
  • 示例:

    func ExampleReadLines() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_content")
    		tempFile = gfile.Join(tempDir, fileName)
    	)
    
    	// write contents
    	gfile.PutContents(tempFile, "L1 goframe example content\nL2 goframe example content")
    
    	// read contents
    	gfile.ReadLines(tempFile, func(text string) error {
    		// Process each line
    		fmt.Println(text)
    		return nil
    	})
    
    	// Output:
    	// L1 goframe example content
    	// L2 goframe example content
    }

ReadLinesBytes

  • 说明:以字节形式逐行读取文件内容
  • 示例:

    func ExampleReadLinesBytes() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_content")
    		tempFile = gfile.Join(tempDir, fileName)
    	)
    
    	// write contents
    	gfile.PutContents(tempFile, "L1 goframe example content\nL2 goframe example content")
    
    	// read contents
    	gfile.ReadLinesBytes(tempFile, func(bytes []byte) error {
    		// Process each line
    		fmt.Println(bytes)
    		return nil
    	})
    
    	// Output:
    	// [76 49 32 103 111 102 114 97 109 101 32 101 120 97 109 112 108 101 32 99 111 110 116 101 110 116]
    	// [76 50 32 103 111 102 114 97 109 101 32 101 120 97 109 112 108 101 32 99 111 110 116 101 110 116]
    }

文件/目录复制

Copy

  • 说明:支持复制文件或目录
  • 示例:

    func ExampleCopy() {
    	// init
    	var (
    		srcFileName = "gflie_example.txt"
    		srcTempDir  = gfile.TempDir("gfile_example_copy_src")
    		srcTempFile = gfile.Join(srcTempDir, srcFileName)
    
    		// copy file
    		dstFileName = "gflie_example_copy.txt"
    		dstTempFile = gfile.Join(srcTempDir, dstFileName)
    
    		// copy dir
    		dstTempDir = gfile.TempDir("gfile_example_copy_dst")
    	)
    
    	// write contents
    	gfile.PutContents(srcTempFile, "goframe example copy")
    
    	// copy file
    	gfile.Copy(srcTempFile, dstTempFile)
    
    	// read contents after copy file
    	fmt.Println(gfile.GetContents(dstTempFile))
    
    	// copy dir
    	gfile.Copy(srcTempDir, dstTempDir)
    
    	// list copy dir file
    	fList, _ := gfile.ScanDir(dstTempDir, "*", false)
    	for _, v := range fList {
    		fmt.Println(gfile.Basename(v))
    	}
    
    	// Output:
    	// goframe example copy
    	// gflie_example.txt
    	// gflie_example_copy.txt
    }

主目录

Home

  • 说明:获取运行用户的主目录
  • 示例:

    func ExampleHome() {
    	// user's home directory
    	homePath, _ := gfile.Home()
    	fmt.Println(homePath)
    
    	// May Output:
    	// C:\Users\hailaz
    }

内容替换

ReplaceFile

  • 说明:替换指定文件的指定内容为新内容
  • 示例:

    func ExampleReplaceFile() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_replace")
    		tempFile = gfile.Join(tempDir, fileName)
    	)
    
    	// write contents
    	gfile.PutContents(tempFile, "goframe example content")
    
    	// read contents
    	fmt.Println(gfile.GetContents(tempFile))
    
    	// It replaces content directly by file path.
    	gfile.ReplaceFile("content", "replace word", tempFile)
    
    	fmt.Println(gfile.GetContents(tempFile))
    
    	// Output:
    	// goframe example content
    	// goframe example replace word
    }

ReplaceFileFunc

  • 说明:使用自定义函数替换指定文件内容
  • 示例:

    func ExampleReplaceFileFunc() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_replace")
    		tempFile = gfile.Join(tempDir, fileName)
    	)
    
    	// write contents
    	gfile.PutContents(tempFile, "goframe example 123")
    
    	// read contents
    	fmt.Println(gfile.GetContents(tempFile))
    
    	// It replaces content directly by file path and callback function.
    	gfile.ReplaceFileFunc(func(path, content string) string {
    		// Replace with regular match
    		reg, _ := regexp.Compile(`\d{3}`)
    		return reg.ReplaceAllString(content, "[num]")
    	}, tempFile)
    
    	fmt.Println(gfile.GetContents(tempFile))
    
    	// Output:
    	// goframe example 123
    	// goframe example [num]
    }

ReplaceDir

  • 说明:扫描指定目录,替换符合条件的文件的指定内容为新内容
  • 示例:

    func ExampleReplaceDir() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_replace")
    		tempFile = gfile.Join(tempDir, fileName)
    	)
    
    	// write contents
    	gfile.PutContents(tempFile, "goframe example content")
    
    	// read contents
    	fmt.Println(gfile.GetContents(tempFile))
    
    	// It replaces content of all files under specified directory recursively.
    	gfile.ReplaceDir("content", "replace word", tempDir, "gflie_example.txt", true)
    
    	// read contents
    	fmt.Println(gfile.GetContents(tempFile))
    
    	// Output:
    	// goframe example content
    	// goframe example replace word
    }

ReplaceDirFunc

  • 说明:扫描指定目录,使用自定义函数替换符合条件的文件的指定内容为新内容
  • 示例:

    func ExampleReplaceDirFunc() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_replace")
    		tempFile = gfile.Join(tempDir, fileName)
    	)
    
    	// write contents
    	gfile.PutContents(tempFile, "goframe example 123")
    
    	// read contents
    	fmt.Println(gfile.GetContents(tempFile))
    
    	// It replaces content of all files under specified directory with custom callback function recursively.
    	gfile.ReplaceDirFunc(func(path, content string) string {
    		// Replace with regular match
    		reg, _ := regexp.Compile(`\d{3}`)
    		return reg.ReplaceAllString(content, "[num]")
    	}, tempDir, "gflie_example.txt", true)
    
    	fmt.Println(gfile.GetContents(tempFile))
    
    	// Output:
    	// goframe example 123
    	// goframe example [num]
    
    }

文件时间

MTime

  • 说明:获取路径修改时间
  • 示例:

    func ExampleMTime() {
    	t := gfile.MTime(gfile.TempDir())
    	fmt.Println(t)
    
    	// May Output:
    	// 2021-11-02 15:18:43.901141 +0800 CST
    }

MTimestamp

  • 说明:获取路径修改时间戳(秒)
  • 示例:

    func ExampleMTimestamp() {
    	t := gfile.MTimestamp(gfile.TempDir())
    	fmt.Println(t)
    
    	// May Output:
    	// 1635838398
    }

MTimestampMilli

  • 说明:获取路径修改时间戳(毫秒)
  • 示例:

    func ExampleMTimestampMilli() {
    	t := gfile.MTimestampMilli(gfile.TempDir())
    	fmt.Println(t)
    
    	// May Output:
    	// 1635838529330
    }

大小获取

Size

  • 说明:获取路径大小
  • 示例:

    func ExampleSize() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_size")
    		tempFile = gfile.Join(tempDir, fileName)
    	)
    
    	// write contents
    	gfile.PutContents(tempFile, "0123456789")
    	fmt.Println(gfile.Size(tempFile))
    
    	// Output:
    	// 10
    }

SizeFormat

  • 说明:获取路径大小,并格式化
  • 示例:

    func ExampleSizeFormat() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_size")
    		tempFile = gfile.Join(tempDir, fileName)
    	)
    
    	// write contents
    	gfile.PutContents(tempFile, "0123456789")
    	fmt.Println(gfile.SizeFormat(tempFile))
    
    	// Output:
    	// 10.00B
    }

ReadableSize

  • 说明:获取路径大小,并格式化人类易读
  • 示例:

    func ExampleReadableSize() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_size")
    		tempFile = gfile.Join(tempDir, fileName)
    	)
    
    	// write contents
    	gfile.PutContents(tempFile, "01234567899876543210")
    	fmt.Println(gfile.ReadableSize(tempFile))
    
    	// Output:
    	// 20.00B
    }

StrToSize

  • 说明:大小字符串转换为大小整形
  • 示例:

    func ExampleStrToSize() {
    	size := gfile.StrToSize("100MB")
    	fmt.Println(size)
    
    	// Output:
    	// 104857600
    }

FormatSize

  • 说明:大小整形转换为大小字符串
  • 示例:

    func ExampleFormatSize() {
    	sizeStr := gfile.FormatSize(104857600)
    	fmt.Println(sizeStr)
    	sizeStr0 := gfile.FormatSize(1024)
    	fmt.Println(sizeStr0)
    	sizeStr1 := gfile.FormatSize(999999999999999999)
    	fmt.Println(sizeStr1)
    
    	// Output:
    	// 100.00M
    	// 1.00K
    	// 888.18P
    }

文件排序

SortFiles

  • 说明:排序多个路径
  • 示例:

    func ExampleSortFiles() {
    	files := []string{
    		"/aaa/bbb/ccc.txt",
    		"/aaa/bbb/",
    		"/aaa/",
    		"/aaa",
    		"/aaa/ccc/ddd.txt",
    		"/bbb",
    		"/0123",
    		"/ddd",
    		"/ccc",
    	}
    	sortOut := gfile.SortFiles(files)
    	fmt.Println(sortOut)
    
    	// Output:
    	// [/0123 /aaa /aaa/ /aaa/bbb/ /aaa/bbb/ccc.txt /aaa/ccc/ddd.txt /bbb /ccc /ddd]
    }

文件搜索

  • 说明:在指定目录(默认包含当前目录、运行目录、主函数目录;不会递归子目录)中搜索文件并返回真实路径
  • 示例:

    func ExampleSearch() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_search")
    		tempFile = gfile.Join(tempDir, fileName)
    	)
    
    	// write contents
    	gfile.PutContents(tempFile, "goframe example content")
    
    	// search file
    	realPath, _ := gfile.Search(fileName, tempDir)
    	fmt.Println(gfile.Basename(realPath))
    
    	// Output:
    	// gflie_example.txt
    }

目录扫描

ScanDir

  • 说明:扫描指定目录,可扫描文件或目录,支持递归扫描
  • 示例:

    func ExampleScanDir() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_scan_dir")
    		tempFile = gfile.Join(tempDir, fileName)
    
    		tempSubDir  = gfile.Join(tempDir, "sub_dir")
    		tempSubFile = gfile.Join(tempSubDir, fileName)
    	)
    
    	// write contents
    	gfile.PutContents(tempFile, "goframe example content")
    	gfile.PutContents(tempSubFile, "goframe example content")
    
    	// scans directory recursively
    	list, _ := gfile.ScanDir(tempDir, "*", true)
    	for _, v := range list {
    		fmt.Println(gfile.Basename(v))
    	}
    
    	// Output:
    	// gflie_example.txt
    	// sub_dir
    	// gflie_example.txt
    }

ScanDirFile

  • 说明:扫描指定目录的文件,支持递归扫描
  • 示例:

    func ExampleScanDirFile() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_scan_dir_file")
    		tempFile = gfile.Join(tempDir, fileName)
    
    		tempSubDir  = gfile.Join(tempDir, "sub_dir")
    		tempSubFile = gfile.Join(tempSubDir, fileName)
    	)
    
    	// write contents
    	gfile.PutContents(tempFile, "goframe example content")
    	gfile.PutContents(tempSubFile, "goframe example content")
    
    	// scans directory recursively exclusive of directories
    	list, _ := gfile.ScanDirFile(tempDir, "*.txt", true)
    	for _, v := range list {
    		fmt.Println(gfile.Basename(v))
    	}
    
    	// Output:
    	// gflie_example.txt
    	// gflie_example.txt
    }

ScanDirFunc

  • 说明:扫描指定目录(自定义过滤方法),可扫描文件或目录,支持递归扫描
  • 示例:

    func ExampleScanDirFunc() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_scan_dir_func")
    		tempFile = gfile.Join(tempDir, fileName)
    
    		tempSubDir  = gfile.Join(tempDir, "sub_dir")
    		tempSubFile = gfile.Join(tempSubDir, fileName)
    	)
    
    	// write contents
    	gfile.PutContents(tempFile, "goframe example content")
    	gfile.PutContents(tempSubFile, "goframe example content")
    
    	// scans directory recursively
    	list, _ := gfile.ScanDirFunc(tempDir, "*", true, func(path string) string {
    		// ignores some files
    		if gfile.Basename(path) == "gflie_example.txt" {
    			return ""
    		}
    		return path
    	})
    	for _, v := range list {
    		fmt.Println(gfile.Basename(v))
    	}
    
    	// Output:
    	// sub_dir
    }

ScanDirFileFunc

  • 说明:扫描指定目录的文件(自定义过滤方法),支持递归扫描
  • 示例:

    func ExampleScanDirFileFunc() {
    	// init
    	var (
    		fileName = "gflie_example.txt"
    		tempDir  = gfile.TempDir("gfile_example_scan_dir_file_func")
    		tempFile = gfile.Join(tempDir, fileName)
    
    		fileName1 = "gflie_example_ignores.txt"
    		tempFile1 = gfile.Join(tempDir, fileName1)
    
    		tempSubDir  = gfile.Join(tempDir, "sub_dir")
    		tempSubFile = gfile.Join(tempSubDir, fileName)
    	)
    
    	// write contents
    	gfile.PutContents(tempFile, "goframe example content")
    	gfile.PutContents(tempFile1, "goframe example content")
    	gfile.PutContents(tempSubFile, "goframe example content")
    
    	// scans directory recursively exclusive of directories
    	list, _ := gfile.ScanDirFileFunc(tempDir, "*.txt", true, func(path string) string {
    		// ignores some files
    		if gfile.Basename(path) == "gflie_example_ignores.txt" {
    			return ""
    		}
    		return path
    	})
    	for _, v := range list {
    		fmt.Println(gfile.Basename(v))
    	}
    
    	// Output:
    	// gflie_example.txt
    	// gflie_example.txt
    }

文件/文件夹管理

Mkdir

  • 说明:创建文件夹,支持递归创建(建议采用绝对路径),创建后的文件夹权限为:`drwxr-xr-x`
  • 示例:

    func ExampleMkdir() {
    	// init
    	var (
    		path = gfile.TempDir("gfile_example_basic_dir")
    	)
    
    	// Creates directory
    	gfile.Mkdir(path)
    
    	// Check if directory exists
    	fmt.Println(gfile.IsDir(path))
    
    	// Output:
    	// true
    }

Create

  • 说明:创建文件/文件夹,如果传入的路径中的文件夹不存在,则会自动创建文件夹以及文件,其中创建的文件权限为`-rw-r–r–`。
  • 注意:如果需要创建文件的已存在,则会清空该文件的内容!
  • 示例:

    func ExampleCreate() {
    	// init
    	var (
    		path     = gfile.Join(gfile.TempDir("gfile_example_basic_dir"), "file1")
    		dataByte = make([]byte, 50)
    	)
    	// Check whether the file exists
    	isFile := gfile.IsFile(path)
    
    	fmt.Println(isFile)
    
    	// Creates file with given `path` recursively
    	fileHandle, _ := gfile.Create(path)
    	defer fileHandle.Close()
    
    	// Write some content to file
    	n, _ := fileHandle.WriteString("hello goframe")
    
    	// Check whether the file exists
    	isFile = gfile.IsFile(path)
    
    	fmt.Println(isFile)
    	
    	// Reset file uintptr
    	unix.Seek(int(fileHandle.Fd()), 0, 0)
    	// Reads len(b) bytes from the File
    	fileHandle.Read(dataByte)
    
    	fmt.Println(string(dataByte[:n]))
    
    	// Output:
    	// false
    	// true
    	// hello goframe
    }







Content Menu

  • No labels