go语言之文件处理
1、获取指定路径下的文件夹
//参数:文件路径;是否递归;返回列表
func GetFiles(pathName string, recursive bool, f *[]string) error { rd, err := ioutil.ReadDir(pathName) if err != nil { return err } for _, fi := range rd { if fi.IsDir() { if recursive == true { err = GetFiles(pathName+"/"+fi.Name(), recursive, f) if err != nil { return err } } } else { *f = append(*f, pathName+"/"+fi.Name()) } } return nil }
2、读取excel文件
func ReadExcel(excelPath string) (*[][]string, error) { var content [][]string xlsxRead, err := excelize.OpenFile(excelPath) if err != nil { return nil, err } sheet := xlsxRead.GetActiveSheetIndex() name := xlsxRead.GetSheetName(sheet) // log.Println("sheet name is " + name) content = xlsxRead.GetRows(name) // log.Println(content) return &content, nil }
3、压缩文件
func Zip(srcFile string, destZip string) error { zipFile, err := os.Create(destZip) if err != nil { return err } defer zipFile.Close() archive := zip.NewWriter(zipFile) defer archive.Close() filepath.Walk(srcFile, func(path string, info os.FileInfo, err error) error { if err != nil { return err } header, err := zip.FileInfoHeader(info) if err != nil { return err } header.Name = strings.TrimPrefix(path, filepath.Dir(srcFile)+"/") // header.Name = path if info.IsDir() { header.Name += "/" } else { header.Method = zip.Deflate } writer, err := archive.CreateHeader(header) if err != nil { return err } if !info.IsDir() { file, err := os.Open(path) if err != nil { return err } defer file.Close() _, err = io.Copy(writer, file) } return err }) return err }
func Tar(source string) error { // tar --directory=files/source_data_export/20220324-121511 -cvf files/source_data_export/20220324-121511/0.tar 0/ splitResult := strings.Split(source, "/") basePath := strings.Join(splitResult[0:len(splitResult)-1], "/") dirName := splitResult[len(splitResult)-1] cmd := exec.Command("tar", "--directory", basePath, "-cvf", source+".tar", dirName) //阻塞至等待命令执行完成 err := cmd.Run() if err != nil { return err } return nil }
4、解压文件
func Unzip(zipFile string, destDir string) error { zipReader, err := zip.OpenReader(zipFile) if err != nil { return err } defer zipReader.Close() for _, f := range zipReader.File { filePath := filepath.Join(destDir, f.Name) if f.FileInfo().IsDir() { err = os.MkdirAll(filePath, os.ModePerm) if err != nil { return err } } else { if err = os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil { return err } inFile, err := f.Open() if err != nil { return err } defer inFile.Close() outFile, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) if err != nil { return err } defer outFile.Close() _, err = io.Copy(outFile, inFile) if err != nil { return err } } } return nil }
5、判断文件是否存在
func IsExist(path string) bool { _, err := os.Stat(path) if err != nil { if os.IsExist(err) { return true } if os.IsNotExist(err) { return false } fmt.Println(err) return false } return true }
// Exists 判断所给路径文件/文件夹是否存在
func Exists(path string) bool {
_, err := os.Stat(path) //os.Stat获取文件信息
if err != nil {
if os.IsExist(err) {
return true
}
return false
}
return true
}
6、复制文件
func Copy(srcFile, dstFile string) error { sourceFileStat, err := os.Stat(srcFile) if err != nil { return err } if !sourceFileStat.Mode().IsRegular() { return fmt.Errorf("%s is not a regular file", srcFile) } source, err := os.Open(srcFile) if err != nil { return err } defer source.Close() destination, err := os.Create(dstFile) if err != nil { return err } defer destination.Close() _, err = io.Copy(destination, source) return err }
7、删除文件
func Remove(filePath string) error { var err error if !Exists(filePath) { err = fmt.Errorf("路径不存在") return err } err = os.Remove(filePath) if err != nil { return err } return nil }
8、读写json文件
func WriteJson(data interface{}, path string) error { fmt.Println(data) // jsonByte, err := json.Marshal(data) jsonByte, err := json.MarshalIndent(data, "", " ") fp, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0755) if err != nil { return err } defer fp.Close() _, err = fp.Write(jsonByte) if err != nil { return err } return nil } func ReadJson(path string) (interface{}, error) { //打开文件 jsonFile, err := os.Open(path) if err != nil { return nil, err } defer jsonFile.Close() //读取为[]bytes类型 byteData, err := ioutil.ReadAll(jsonFile) if err != nil { return nil, err } var returnData interface{} err = json.Unmarshal(byteData, &returnData) if err != nil { return nil, err } return returnData, nil }
9、判断文件夹是否存在
// PathExists 判断文件夹是否存在 func PathExists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return false, err }