Browse Source

添加带缓存读取文件的函数

yjp 2 months ago
parent
commit
4a0b382fc4
3 changed files with 72 additions and 2 deletions
  1. 56 2
      fileutils/fileutils.go
  2. 15 0
      fileutils/fileutils_test.go
  3. 1 0
      fileutils/test_dir/test.txt

+ 56 - 2
fileutils/fileutils.go

@@ -10,6 +10,11 @@ import (
 	"strings"
 )
 
+// PathExists 检查对应路径的文件或目录是否存在
+// 参数:
+// path: 文件或目录的路径
+// 返回值:
+// 对应路径的文件或目录是否存在
 func PathExists(path string) bool {
 	_, err := os.Stat(path)
 	if err == nil {
@@ -23,6 +28,11 @@ func PathExists(path string) bool {
 	return false
 }
 
+// GetDirFiles 获取目录下的文件
+// 参数
+// dir: 目录的路径
+// 返回值:
+// 目录下的文件路径(用dir拼接,dir是绝对路径就是绝对路径,dir是相对路径就是相对路径)和错误
 func GetDirFiles(dir string) ([]string, error) {
 	dirList, err := os.ReadDir(dir)
 	if err != nil {
@@ -47,6 +57,44 @@ func GetDirFiles(dir string) ([]string, error) {
 	return filesRet, nil
 }
 
+// ReadFileWithBuffer 带缓冲读文件,一般用于大文件读取
+// 参数
+// filePath: 文件的路径
+// bufferSize: 缓冲大小,每次最多读取的字节数
+// readCallback: 每次读取回调
+// 返回值:
+// 错误
+func ReadFileWithBuffer(filePath string, bufferSize int, readCallback func(b []byte)) error {
+	file, err := os.Open(filePath)
+	if err != nil {
+		return err
+	}
+
+	for {
+		buffer := make([]byte, bufferSize)
+		readSize, err := file.Read(buffer)
+		if err != nil && err != io.EOF {
+			return err
+		}
+
+		if readCallback != nil {
+			readCallback(buffer[:readSize])
+		}
+
+		if err != nil && err == io.EOF {
+			break
+		}
+	}
+
+	return nil
+}
+
+// ZipDir zip压缩目录
+// 参数
+// dirPath: 目录的路径
+// savePath: 生成zip文件的路径
+// 返回值:
+// 错误
 func ZipDir(dirPath string, savePath string) error {
 	archive, err := os.Create(savePath)
 	if err != nil {
@@ -96,8 +144,14 @@ func ZipDir(dirPath string, savePath string) error {
 	return nil
 }
 
-func UnzipFile(srcFilePath string, destDir string) error {
-	srcFile, err := os.Open(srcFilePath)
+// UnzipFile 解压缩zip文件
+// 参数
+// zipFilePath: zip文件路径
+// destDir: 解压缩的目的目录
+// 返回值:
+// 错误
+func UnzipFile(zipFilePath string, destDir string) error {
+	srcFile, err := os.Open(zipFilePath)
 	if err != nil {
 		return err
 	}

+ 15 - 0
fileutils/fileutils_test.go

@@ -1,6 +1,7 @@
 package fileutils
 
 import (
+	"bytes"
 	"os"
 	"path/filepath"
 	"testing"
@@ -26,6 +27,20 @@ func TestGetDirFiles(t *testing.T) {
 	checkTestDir(t, testDirRelativePath)
 }
 
+func TestReadFileWithBuffer(t *testing.T) {
+	buffer := bytes.Buffer{}
+	err := ReadFileWithBuffer(filepath.Join(testDirRelativePath, "test.txt"), 1, func(b []byte) {
+		buffer.Write(b)
+	})
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	if buffer.String() != "test content" {
+		t.Fatal("读取失败")
+	}
+}
+
 func TestZip(t *testing.T) {
 	zipFileRelativePath := "test.zip"
 	destUnzipFileDir := "./unzip_file_test_dir"

+ 1 - 0
fileutils/test_dir/test.txt

@@ -0,0 +1 @@
+test content