• Go语言入门心法(十一): 文件处理




    Go语言入门心法(一): 基础语法

    Go语言入门心法(二): 结构体

    Go语言入门心法(三): 接口

    Go语言入门心法(四): 异常体系

     Go语言入门心法(五): 函数

    Go语言入门心法(六): HTTP面向客户端|服务端编程

    Go语言入门心法(七): 并发与通道

    Go语言入门心法(八): mysql驱动安装报错onnection failed

    Go语言入门心法(九): 引入三方依赖

    Go语言入门心法(十):Go语言操作MYSQL(CRUD)|事务处理

    Go语言入门心法(十一): 文件处理

    Go语言入门心法(十二): GORM映射框架

    Go语言入门心法(十三): 反射认知升维




     一:go语言对文件处理认知

    计算机文件是以硬盘为载体的信息存储集合,文件可以是文本,图片,程序等
    
       文件通常被称为两类:
          文本文件和二进制文件
       通常我们对文件的操作有,创建文件,删除文件,读|写文件,修改文件等基础的操作,go语言中计算机对文件的操作主要会用到I/O操作库,该库主要封装了如下的几个包
       (1) io-------为IO原语(I/O primitives)提供基本的接口
       (2) io/ioutil----------封装了一些使用的I/O函数
       (3) fmt----------实现格式化I/O,类似于C语言中的printf()和scanf()函数
       (4) bufio--------实现带缓冲的I/O

    实例一: 读取文件或者递归读取文件夹下的子目录

    1. package main
    2. import (
    3. "fmt"
    4. "io/fs"
    5. "io/ioutil"
    6. "path/filepath"
    7. )
    8. /*
    9. 计算机文件是以硬盘为载体的信息存储集合,文件可以是文本,图片,程序等
    10. 文件通常被称为两类:
    11. 文本文件和二进制文件
    12. 通常我们对文件的操作有,创建文件,删除文件,读|写文件,修改文件等基础的操作,go语言中计算机对文件的操作主要会用到I/O操作库,该库主要封装了如下的几个包
    13. (1) io-------为IO原语(I/O primitives)提供基本的接口
    14. (2) io/ioutil----------封装了一些使用的I/O函数
    15. (3) fmt----------实现格式化I/O,类似于C语言中的printf()和scanf()函数
    16. (4) bufio--------实现带缓冲的I/O
    17. */
    18. func main() {
    19. // 读取目录
    20. dir, err := ioutil.ReadDir("C:\\Users")
    21. if err != nil {
    22. fmt.Printf("系统异常: %s", err.Error())
    23. }
    24. for _, file := range dir {
    25. if file.IsDir() {
    26. fmt.Printf("读取到目录Users目录下的子目录: %s \n", file.Name())
    27. } else {
    28. fmt.Printf("读取到目录Users目录文件: %s \n", file.Name())
    29. }
    30. }
    31. println()
    32. println("通过os.FileIno接口可以获取到的信息如下:\n")
    33. println(`
    34. // A FileInfo describes a file and is returned by Stat.
    35. type FileInfo interface {
    36. Name() string // base name of the file
    37. Size() int64 // length in bytes for regular files; system-dependent for others
    38. Mode() FileMode // file mode bits
    39. ModTime() time.Time // modification time
    40. IsDir() bool // abbreviation for Mode().IsDir()
    41. Sys() any // underlying data source (can return nil)
    42. `)
    43. println()
    44. fmt.Printf("获取一个目录下的所有文件名(包括子文件夹内的所有文件),也就是递归遍历一个文件夹内所有的文件。\n Go语言提供了一个更加方便的操作函数,这个函数位于path/filePath库中" +
    45. "\n func Walk(root string,walkFn WalkFunc) error ")
    46. WalkDir("C:\\Windows\\Temp")
    47. }
    48. // WalkDir 打印指定目录下的所有文件,包括子目录
    49. func WalkDir(path string) {
    50. err := filepath.Walk(path, func(path string, file fs.FileInfo, err error) error {
    51. if file == nil {
    52. return err
    53. }
    54. if file.IsDir() {
    55. return nil
    56. }
    57. println(path)
    58. return nil
    59. })
    60. if err != nil {
    61. fmt.Printf("filepaht.Walk() returned %v \n", err)
    62. }
    63. }

    运行效果:


    GOROOT=D:\program_file_worker\go1.20 #gosetup
    GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
    D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPFileToGrammarReadDir_go.exe D:\program_file\go_workspace\org.jd.data\file\OOPFileToGrammarReadDir.go #gosetup
    C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPFileToGrammarReadDir_go.exe
    读取到目录Users目录下的子目录: Administrator
    读取到目录Users目录文件: All Users
    读取到目录Users目录下的子目录: Default
    读取到目录Users目录文件: Default User
    读取到目录Users目录下的子目录: Public
    读取到目录Users目录文件: desktop.ini

    通过os.FileIno接口可以获取到的信息如下:


        // A FileInfo describes a file and is returned by Stat.
            type FileInfo interface {
                    Name() string       // base name of the file
                    Size() int64        // length in bytes for regular files; system-dependent for others

                    Mode() FileMode     // file mode bits
                    ModTime() time.Time // modification time
                    IsDir() bool        // abbreviation for Mode().IsDir()
                    Sys() any           // underlying data source (can return nil)


    获取一个目录下的所有文件名(包括子文件夹内的所有文件),也就是递归遍历一个文件夹内
    所有的文件。
     Go语言提供了一个更加方便的操作函数,这个函数位于path/filePath库中
      func Walk(root string,walkFn WalkFunc) error C:\Windows\Temp\MpSigStub.log
    C:\Windows\Temp\VS`0)IZ2Y%4ZC@2APXV7SL9.tmp
    C:\Windows\Temp\YH-DESKTOP-WORK-20231014-2312.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231020-2103.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231021-0927.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231021-0933.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231021-0933a.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231021-0933b.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231021-0940.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231021-0956.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231021-1122.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231021-1346.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231021-1353.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231021-1633.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231021-1638.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231021-1747.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231021-1810.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231021-2104.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231021-2228.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231021-2238.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231021-2250.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231021-2256.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231021-2312.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231021-2335.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231021-2339.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231022-0815.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231022-0818.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231022-0836.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231022-0851.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231022-0921.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231022-0931.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231022-0933.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231022-1023.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231022-1057.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231022-1205.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231022-1221.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231022-1253.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231022-1303.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231022-1426.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231022-1653.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231022-1813.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231022-2159.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231023-0900.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231023-0905.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231023-0906.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231023-0915.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231023-0944.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231023-1115.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231023-1225.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231023-1552.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231023-1707.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231023-1718.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231023-1732.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231023-1805.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231023-1838.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231023-1948.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231023-2035.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231023-2307.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231024-2140.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231025-0831.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231025-0836.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231025-0837.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231025-0837a.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231025-0845.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231025-0902.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231025-1324.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231025-1337.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231025-1508.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231025-1722.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231025-1751.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231025-1759.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231025-1910.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231025-2118.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231025-2159.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231026-0848.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231026-0854.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231026-0854a.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231026-0859.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231026-1119.logg
    C:\Windows\Temp\YH-DESKTOP-WORK-20231026-1203.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231026-1218.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231026-1321.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231026-1403.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231026-1523.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231026-1630.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231026-1726.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231026-1849.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231026-1922.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231026-1940.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231026-1947.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231026-2120.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231027-0852.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231027-0852a.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231027-0852b.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231027-0854.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231027-0857.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231027-0908.log
    C:\Windows\Temp\YH-DESKTOP-WORK-20231027-1136.log
    C:\Windows\Temp\vminst.log

    Process finished with the exit code 0
     


    二:递归创建文件夹


    1. package main
    2. import (
    3. "fmt"
    4. "io/fs"
    5. "os"
    6. "path/filepath"
    7. )
    8. /*
    9. 创建目录与递归创建目录
    10. */
    11. func main() {
    12. println("===========================开始创建目录==================================\n")
    13. println()
    14. createDirAll("C:\\Users", "test\\dir1\\dir2")
    15. createDirAll("C:\\Windows\\Temp", "dir1\\dir2\\test")
    16. println()
    17. println("===========================创建目录结束==================================\n")
    18. println()
    19. println("=======================读取创建的目录==============================================")
    20. walkDir("C:\\Users\\test")
    21. walkDir("C:\\Windows\\Temp\\test")
    22. }
    23. // 创建目录
    24. func createDirAll(path string, dirName string) {
    25. dirPath := path + "\\" + dirName
    26. // 0777也可以os.ModePerm
    27. fmt.Println("Create Dir => " + dirPath)
    28. err := os.MkdirAll(dirPath, 0777)
    29. if err != nil {
    30. fmt.Printf("文件创建失败: %s \n", dirPath)
    31. } else {
    32. fmt.Printf("文件创建成功: %s", dirPath)
    33. fmt.Println("Create Dir => " + dirPath)
    34. }
    35. os.Chmod(dirPath, 0777)
    36. }
    37. // walkDir 打印指定目录下的所有文件,包括子目录
    38. func walkDir(path string) {
    39. err := filepath.Walk(path, func(path string, file fs.FileInfo, err error) error {
    40. if file == nil {
    41. return err
    42. }
    43. if file.IsDir() {
    44. println("目录: ", path)
    45. return nil
    46. }
    47. println("文件: ", path)
    48. return nil
    49. })
    50. if err != nil {
    51. fmt.Printf("文件或者目录不存在: %v \n", err.Error())
    52. }
    53. }

    运行效果:


    GOROOT=D:\program_file_worker\go1.20 #gosetup
    GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
    D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPFileToGrammarMkdirAndMkdirAll_go.exe D:\program_file\go_workspace\org.jd.data\file\OOPFileToGrammarMkdirAndMkdirAll.go #gosetup
    C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPFileToGrammarMkdirAndMkdirAll_go.exe
    ===========================开始创建目录==================================


    Create Dir => C:\Users\test\dir1\dir2
    文件创建失败: C:\Users\test\dir1\dir2
    Create Dir => C:\Windows\Temp\dir1\dir2\test
    文件创建成功: C:\Windows\Temp\dir1\dir2\testCreate Dir => C:\Windows\Temp\dir1\dir2\test


    ===========================创建目录结束==================================


    =======================读取创建的目录==============================================
    文件或者目录不存在: CreateFile C:\Users\test: The system cannot find the file specified.
    目录:  C:\Windows\Temp\test

    Process finished with the exit code 0
     

    三:删除空|非空目录

    删除文件目录:

            (1)删除文件目录可以使用接口: func Remove(name string) error ;Remove删除name指定的文件或目录。此接口只能删除空文件夹,
             如果文件夹不为空,则会删除失败,返回"文件夹为非空"错误
            (2)对于文件夹不为空的情况,可以使用RemoveAll(path string) error 这个接口


    1. package main
    2. import (
    3. "fmt"
    4. "os"
    5. )
    6. /*
    7. 删除文件目录:
    8. (1)删除文件目录可以使用接口: func Remove(name string) error ;Remove删除name指定的文件或目录。此接口只能删除空文件夹,
    9. 如果文件夹不为空,则会删除失败,返回"文件夹为非空"错误
    10. (2)对于文件夹不为空的情况,可以使用RemoveAll(path string) error 这个接口
    11. */
    12. func main() {
    13. println("====================================删除空目录开始==============================")
    14. deleteEmptyDir("D:\\program files\\test")
    15. println("====================================删除空目录结束==============================")
    16. println()
    17. println()
    18. println("====================================删除非空目录开始==============================")
    19. deleteNotEmpty("D:\\program files\\test")
    20. println("====================================删除非空目录结束==============================")
    21. }
    22. // 删除空目录
    23. func deleteEmptyDir(dirPath string) {
    24. fmt.Println("Delete Dir => " + dirPath)
    25. err := os.Remove(dirPath)
    26. if err != nil {
    27. fmt.Println(err)
    28. } else {
    29. fmt.Println("Delete Success!")
    30. }
    31. }
    32. // 删除非空目录
    33. func deleteNotEmpty(dirPath string) {
    34. fmt.Println("Delete Dir => " + dirPath)
    35. err := os.RemoveAll(dirPath)
    36. if err != nil {
    37. fmt.Println(err)
    38. } else {
    39. fmt.Println("Deletes Success!")
    40. }
    41. }

    运行效果:


    GOROOT=D:\program_file_worker\go1.20 #gosetup
    GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
    D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_file.exe D:\program_file\go_workspace\org.jd.data\file\OOPFileToGrammarRemoveAndRemoveAll.go #gosetup
    C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_file.exe
    ====================================删除空目录开始==============================
    Delete Dir => D:\program files\test
    remove D:\program files\test: The directory is not empty.
    ====================================删除空目录结束==============================


    ====================================删除非空目录开始==============================
    Delete Dir => D:\program files\test
    Deletes Success!
    ====================================删除非空目录结束==============================

    Process finished with the exit code 0

    四:打开及读取文件


    1. package main
    2. import (
    3. "fmt"
    4. "os"
    5. )
    6. /*
    7. 打开及读取文件
    8. */
    9. func main() {
    10. var filePath string = "C:\\Windows\\Temp\\test.txt"
    11. openExistElseCreate(filePath)
    12. println()
    13. readFile(filePath)
    14. }
    15. // 以只读打开一个文件,如果文件不存在,则创建一个文件
    16. func openExistElseCreate(filePath string) {
    17. file, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE, 0766)
    18. if err != nil {
    19. fmt.Println(err)
    20. } else {
    21. fmt.Println(file)
    22. file.Close()
    23. }
    24. println()
    25. fmt.Println("os关于系统文件相关常量定义")
    26. println(`
    27. const (
    28. // Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
    29. O_RDONLY int = syscall.O_RDONLY // open the file read-only.
    30. O_WRONLY int = syscall.O_WRONLY // open the file write-only.
    31. O_RDWR int = syscall.O_RDWR // open the file read-write.
    32. // The remaining values may be or'ed in to control behavior.
    33. O_APPEND int = syscall.O_APPEND // append data to the file when writing.
    34. O_CREATE int = syscall.O_CREAT // create a new file if none exists.
    35. O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist.
    36. O_SYNC int = syscall.O_SYNC // open for synchronous I/O.
    37. O_TRUNC int = syscall.O_TRUNC // truncate regular writable file when opened.
    38. )
    39. `)
    40. }
    41. func readFile(pathFile string) {
    42. // 读取文件内容
    43. file, err := os.Open(pathFile)
    44. if err != nil {
    45. fmt.Println(err)
    46. return
    47. }
    48. // 创建byte的slice用于接收文件读取数据
    49. buf := make([]byte, 1024)
    50. println()
    51. println()
    52. fmt.Println("以下是文件内容:")
    53. // 循环读取
    54. for {
    55. // Read函数会改变文件当前偏移量
    56. len, _ := file.Read(buf)
    57. // 读取字节数为0时跳出循环
    58. if len == 0 {
    59. break
    60. }
    61. fmt.Println(string(buf))
    62. }
    63. defer file.Close()
    64. }

    运行效果:


    GOROOT=D:\program_file_worker\go1.20 #gosetup
    GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
    D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_file__1_.exe D:\program_file\go_workspace\org.jd.data\file\OOPFileToGrammarOpenAndRead.go #gosetup
    C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_file__1_.exe
    &{0xc00009aa00}

    os关于系统文件相关常量定义

          const (
                    // Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.

                    O_RDONLY int = syscall.O_RDONLY // open the file read-only.
                    O_WRONLY int = syscall.O_WRONLY // open the file write-only.
                    O_RDWR   int = syscall.O_RDWR   // open the file read-write.
                    // The remaining values may be or'ed in to control behavior.
                    O_APPEND int = syscall.O_APPEND // append data to the file when writing.

                    O_CREATE int = syscall.O_CREAT  // create a new file if none exists.

                    O_EXCL   int = syscall.O_EXCL   // used with O_CREATE, file must not exist.

                    O_SYNC   int = syscall.O_SYNC   // open for synchronous I/O.
                    O_TRUNC  int = syscall.O_TRUNC  // truncate regular writable file when opened.
         )


    以下是文件内容:
    你好
    你好

    good mooning !

    Process finished with the exit code 0
     


    五:从指定位置读取文件内容

    读取文件函数认知升维:
    
          (1)Read与ReadAt函数的区别:前者从文件当前偏移量处开始读取,且会改变文件当前的偏移量;而后者从off指定的位置开始读取,
           且不会改变文件当前偏移量
          (2)当遇到特别大的文件,并且只需要读取文件最后部分的内容时,Read接口就不能满足我们需要了,这时就可以使用另外一个读取接口ReadAt;
          这个接口可以指定从指定文件的位置开始读取。
    

    1. package main
    2. import (
    3. "fmt"
    4. "os"
    5. )
    6. /*
    7. 读取文件函数认知升维:
    8. (1)Read与ReadAt函数的区别:前者从文件当前偏移量处开始读取,且会改变文件当前的偏移量;而后者从off指定的位置开始读取,
    9. 且不会改变文件当前偏移量
    10. (2)当遇到特别大的文件,并且只需要读取文件最后部分的内容时,Read接口就不能满足我们需要了,这时就可以使用另外一个读取接口ReadAt;
    11. 这个接口可以指定从指定文件的位置开始读取。
    12. */
    13. func main() {
    14. pathFile := "C:\\Windows\\Temp\\readAt.txt"
    15. readFileByLocation(pathFile)
    16. }
    17. func readFileByLocation(path string) {
    18. // 读取文件内容
    19. file, err := os.Open(path)
    20. if err != nil {
    21. fmt.Println(err)
    22. return
    23. }
    24. // 创建byte的slice用于接收文件读取数据
    25. buf := make([]byte, 1024)
    26. fmt.Println("以下是文件的内容: ")
    27. // 读取偏移9字节的数据
    28. _, _ = file.ReadAt(buf, 9)
    29. fmt.Println(string(buf))
    30. _ = file.Close()
    31. }

    运行效果:


    GOROOT=D:\program_file_worker\go1.20 #gosetup
    GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
    D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_file__2_.exe D:\program_file\go_workspace\org.jd.data\file\OOPFileToGrammarReadAt.go #gosetup
    C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_file__2_.exe
    以下是文件的内容:

    中国加油
    中国加油
    中国加油
    中国加油
    中国加油

    Process finished with the exit code 0
     


    源文件:


     六:写入数据|从指定偏移开始位置写入数据

    go语言文件写入认知:
    
    与之前的文件读取比较,向文件写入内容也有两个接口,分别为Write和WriteAt
    (1)func (f *File) Write(b []byte) (n int,err error)
    Write向文件中写入len(b)字节数据,它返回写入的字节数和可能遇到的任何数据。如果返回值为n!=len(b),
    则该方法会返回一个非nil的错误
       (2)func (f *File) WriteAt(b []byte, off int64) (n int, err error)
        WriteAt函数在指定的位置(相对于文件开始位置),写入len(b)字节数据。它返回写入的字节数和可能遇到的任何错误。
        如果返回值为n != len(b),则会返回一个非nil的错误

    1. package main
    2. import (
    3. "fmt"
    4. "os"
    5. "strconv"
    6. )
    7. /*
    8. go语言文件写入认知:
    9. 与之前的文件读取比较,向文件写入内容也有两个接口,分别为Write和WriteAt
    10. (1)func (f *File) Write(b []byte) (n int,err error)
    11. Write向文件中写入len(b)字节数据,它返回写入的字节数和可能遇到的任何数据。如果返回值为n!=len(b),
    12. 则该方法会返回一个非nil的错误
    13. (2)func (f *File) WriteAt(b []byte, off int64) (n int, err error)
    14. WriteAt函数在指定的位置(相对于文件开始位置),写入len(b)字节数据。它返回写入的字节数和可能遇到的任何错误。
    15. 如果返回值为n != len(b),则会返回一个非nil的错误
    16. */
    17. func main() {
    18. pathFile := "C:\\Windows\\Temp\\11.txt"
    19. writeData(pathFile)
    20. println()
    21. writeDataAtLocation("C:\\Windows\\Temp\\Write.txt")
    22. }
    23. // 从文件开头写入数据
    24. func writeData(path string) {
    25. file, err := os.Create(path)
    26. if err != nil {
    27. fmt.Println(err)
    28. return
    29. }
    30. data := "你好,欢迎来到go语言操作文件相关的方法\r\n"
    31. for i := 0; i < 10; i++ {
    32. // 写入byte的slice数据
    33. file.Write([]byte(data))
    34. }
    35. println("数据写入成功")
    36. defer file.Close()
    37. println()
    38. println()
    39. println("=============指定偏移量写入数据====================")
    40. println()
    41. }
    42. // 从指定的位置开始写入数据,这个指定的位置是相对于开始位置
    43. func writeDataAtLocation(path string) {
    44. file, err := os.Create(path)
    45. if err != nil {
    46. fmt.Println(err)
    47. }
    48. for i := 0; i < 5; i++ {
    49. // 按指定偏移量写入数据
    50. ix := i * 64
    51. file.WriteAt([]byte("这是指定偏移位置写入到数据"+strconv.Itoa(i)+"\r\n"), int64(ix))
    52. }
    53. println("从指定的偏移位置,写入数据成功!")
    54. defer file.Close()
    55. }

    运行效果:


    GOROOT=D:\program_file_worker\go1.20 #gosetup
    GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
    D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPFileToGrammarWrite_go.exe D:\program_file\go_workspace\org.jd.data\file\OOPFileToGrammarWrite.go #gosetup
    C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPFileToGrammarWrite_go.exe
    数据写入成功


    =============指定偏移量写入数据====================


    从指定的偏移位置,写入数据成功!

    Process finished with the exit code 0


     


     七:删除指定文件|文件夹下的所有文件

    删除文件的接口与删除目录的接口一致


    1. package main
    2. import (
    3. "fmt"
    4. "os"
    5. )
    6. /*
    7. 删除文件目录:
    8. (1)删除文件目录可以使用接口: func Remove(name string) error ;Remove删除name指定的文件或目录。此接口只能删除空文件夹,
    9. 如果文件夹不为空,则会删除失败,返回"文件夹为非空"错误
    10. (2)对于文件夹不为空的情况,可以使用RemoveAll(path string) error 这个接口
    11. */
    12. func main() {
    13. println("====================================删除空目录开始==============================")
    14. deletePathFile("C:\\Windows\\Temp\\Write.txt")
    15. println("====================================删除空目录结束==============================")
    16. println()
    17. println()
    18. println("====================================删除非空目录下的所有文件开始==============================")
    19. deleteDirLowerAllFiles("C:\\Windows\\Temp\\")
    20. println("====================================删除非空目录下的所有文件结束==============================")
    21. }
    22. // 删除指定路径的文件
    23. func deletePathFile(dirPath string) {
    24. fmt.Println("Delete Dir => " + dirPath)
    25. err := os.Remove(dirPath)
    26. if err != nil {
    27. fmt.Println(err)
    28. } else {
    29. fmt.Println("Delete Success!")
    30. }
    31. }
    32. // 删除非空目录下的所有文件
    33. func deleteDirLowerAllFiles(dirPath string) {
    34. fmt.Println("Delete Dir => " + dirPath)
    35. err := os.RemoveAll(dirPath)
    36. if err != nil {
    37. fmt.Println(err)
    38. } else {
    39. fmt.Println("Deletes Success!")
    40. }
    41. }

    运行效果:


    GOROOT=D:\program_file_worker\go1.20 #gosetup
    GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
    D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPFileToGrammarFileRemoveAndRemoveAll_go.exe D:\program_file\go_workspace\org.jd.data\file\OOPFileToGrammarFileRemoveAndRemoveAll.go #gosetup
    C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPFileToGrammarFileRemoveAndRemoveAll_go.exe
    ====================================删除空目录开始==============================Delete Dir => C:\Windows\Temp\Write.txt
    Delete Success!
    ====================================删除空目录结束==============================

    ====================================删除非空目录下的所有文件开始==============================
    Delete Dir => C:\Windows\Temp\
    open C:\Windows\Temp\\vmware-SYSTEM: Access is denied.
    ====================================删除非空目录下的所有文件结束==============================

    Process finished with the exit code 0


     八:JSON文件的编码处理

    JSON文件的编码处理:
    
       json(JavaScript Object Notation,JS对象简谱)是一种轻量级数据交换格式,基本上所有的语言都支持JSON数据编码和解码;
       编码JSON,即从其他的数据类型编码成JSON字符串,这个过程使用如下接口
       func Marshal(v interface{}) ([]byte, error);
       为了使JSON字符串更加直观,可以使用MarshalIndent函数进行输出格式化操作
       func MarshalIndent(v interface{},prefix,indent string)  ([]byte,error);该函数会使用缩进将输出格式化

    8.1 Map类型数据转换为Json格式数据

    1. package main
    2. import (
    3. "encoding/json"
    4. "fmt"
    5. )
    6. /*
    7. JSON文件的编码处理:
    8. json(JavaScript Object Notation,JS对象简谱)是一种轻量级数据交换格式,基本上所有的语言都支持JSON数据编码和解码;
    9. 编码JSON,即从其他的数据类型编码成JSON字符串,这个过程使用如下接口
    10. func Marshal(v interface{}) ([]byte, error);
    11. 为了使JSON字符串更加直观,可以使用MarshalIndent函数进行输出格式化操作
    12. func MarshalIndent(v interface{},prefix,indent string) ([]byte,error);该函数会使用缩进将输出格式化
    13. */
    14. func main() {
    15. // 创建一个map
    16. m := make(map[string]interface{}, 6)
    17. m["name"] = "王二麻子"
    18. m["age"] = 24
    19. m["sex"] = true
    20. m["birthday"] = "2023-01-012"
    21. m["company"] = "Go重构有限公司"
    22. m["language"] = []string{"Go", "PHP", "Python"}
    23. // 编码为JSON
    24. result, _ := json.Marshal(m)
    25. resultFormat, _ := json.MarshalIndent(m, "", " ")
    26. fmt.Println("result = ", string(result))
    27. println()
    28. fmt.Println("resultFormat = ", string(resultFormat))
    29. }

    运行效果:


    GOROOT=D:\program_file_worker\go1.20 #gosetup
    GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
    D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_file__3_.exe D:\program_file\go_workspace\org.jd.data\file\OOPJSONFileToGrammarMarshal.go #gosetup
    C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_file__3_.exe
    result =  {"age":24,"birthday":"2023-01-012","company":"Go重构有限公司","language":["Go","PHP","Python"],"name":"王二麻子","sex":true}


    resultFormat =  {
        "age": 24,
        "birthday": "2023-01-012",
        "company": "Go重构有限公司",
        "language": [
            "Go",
            "PHP",
            "Python"
        ],
        "name": "王二麻子",
        "sex": true
    }

    Process finished with the exit code 0
     


    8.2 Struct(结构体)类型数据转换为Json格式数据 
    1. package main
    2. import (
    3. "encoding/json"
    4. "fmt"
    5. )
    6. /*
    7. 结构体类型数据解码为JSON的互操作
    8. */
    9. func main() {
    10. // 定义一个结构体变量
    11. person := Person{"隔壁老王", 30, true, "1992-12-12", "中国银行股份有限公司",
    12. []string{"Go从入门到精通", "C语言从精通到放弃", "Python语言大仙", "零基础人生必修升仙指南"}}
    13. result, err := json.Marshal(person)
    14. if err != nil {
    15. fmt.Println(err)
    16. return
    17. }
    18. println("result : ", string(result))
    19. result, err = json.MarshalIndent(person, "", " ")
    20. // 格式化输出json文件
    21. fmt.Println("resultIndent : ", string(result))
    22. }
    23. // Person 定义描述人的结构体
    24. type Person struct {
    25. Name string `json:"name"`
    26. Age int `json:"age"`
    27. Sex bool `json:"sex"`
    28. Birthday string `json:"birthday"`
    29. Company string `json:"company"`
    30. Language []string `json:"language"`
    31. }

    运行效果:


    GOROOT=D:\program_file_worker\go1.20 #gosetup
    GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
    D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPJSONFileToGrammarUnmarshal_go.exe D:\program_file\go_workspace\org.jd.data\file\OOPJSONFileToGrammarUnmarshal.go #gosetup
    C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_OOPJSONFileToGrammarUnmarshal_go.exe
    result :  {"name":"隔壁老王","age":30,"sex":true,"birthday":"1992-12-12","company":"中国银行股份有限公司","language":["Go从入门到精通","C语言从精通到放弃","Python语言大仙","零基础人生必修升仙指南"]}
    resultIndent :  {
      "name": "隔壁老王",
      "age": 30,
      "sex": true,
      "birthday": "1992-12-12",
      "company": "中国银行股份有限公司",
      "language": [
        "Go从入门到精通",
        "C语言从精通到放弃",
        "Python语言大仙",
        "零基础人生必修升仙指南"
      ]
    }

    Process finished with the exit code 0
     


     九:JSON文件的解码处理


    9.1 json字符串解码转换为map类型数据

    1. package main
    2. import (
    3. "fmt"
    4. "github.com/goccy/go-json"
    5. )
    6. /*
    7. Json字符串转换为Map类型的数据
    8. */
    9. func main() {
    10. jsonStr := `
    11. {
    12. "name": "隔壁老王",
    13. "age": 30,
    14. "sex": true,
    15. "birthday": "1992-12-12",
    16. "company": "中国银行股份有限公司",
    17. "language": [
    18. "Go从入门到精通",
    19. "C语言从精通到放弃",
    20. "Python语言修仙之道",
    21. "零基础人生必修升仙指南"
    22. ]
    23. }
    24. `
    25. // 创建一个Map类型的变量
    26. mapResult := make(map[string]interface{}, 6)
    27. // json字符串界面为map类型数据
    28. err := json.Unmarshal([]byte(jsonStr), &mapResult)
    29. if err != nil {
    30. fmt.Println(err)
    31. }
    32. fmt.Println(" mapResult = ", mapResult)
    33. println()
    34. // 类型断言
    35. for key, value := range mapResult {
    36. switch data := value.(type) {
    37. case string:
    38. fmt.Printf("map[%s]的值类型为 string,value = %s \n", key, data)
    39. case float64:
    40. fmt.Printf("map[%s]的值类型为 int,value = %f \n", key, data)
    41. case bool:
    42. fmt.Printf("map[%s]的值类型为 bool,value = %t \n", key, data)
    43. case []string:
    44. fmt.Printf("map[%s]的值类型为 []string,value = %v \n", key, data)
    45. case []interface{}:
    46. fmt.Printf("map[%s]的值类型为 []interface,value = %v \n", key, data)
    47. }
    48. }
    49. }

    运行效果:


    GOROOT=D:\program_file_worker\go1.20 #gosetup
    GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
    D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_file.exe D:\program_file\go_workspace\org.jd.data\file\OOPJSONFileToGrammarMapUnMarshal.go #gosetup
    C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_file.exe
     mapResult =  map[age:30 birthday:1992-12-12 company:中国银行股份有限公司 language:[Go从入门到精通 C语言从精通到放弃 Python语言修仙之道 零基础人生必修升仙指南] name:隔壁老王 sex:true]

    map[birthday]的值类型为 string,value = 1992-12-12
    map[company]的值类型为 string,value = 中国银行股份有限公司
    map[language]的值类型为 []interface,value = [Go从入门到精通 C语言从精通到放弃 Python语言修仙之道 零基础人生必修升仙指南]
    map[name]的值类型为 string,value = 隔壁老王
    map[age]的值类型为 int,value = 30.000000
    map[sex]的值类型为 bool,value = true

    Process finished with the exit code 0


    9.2 json字符串解码转换为Struct(结构体类型)数据

    1. package main
    2. import (
    3. "encoding/json"
    4. "fmt"
    5. )
    6. /*
    7. json字符串界面为struct结构体类型的数据
    8. */
    9. func main() {
    10. jsonStr := `
    11. {
    12. "name": "隔壁老王",
    13. "age": 30,
    14. "sex": true,
    15. "birthday": "1992-12-12",
    16. "company": "中国银行股份有限公司",
    17. "language": [
    18. "Go从入门到精通",
    19. "C语言从精通到放弃",
    20. "Python语言修仙之道",
    21. "零基础人生必修升仙指南"
    22. ]
    23. }
    24. `
    25. // 实例化结构体对象
    26. var person UnPerson
    27. // 解码字符串
    28. err := json.Unmarshal([]byte(jsonStr), &person)
    29. if err != nil {
    30. fmt.Println(err)
    31. }
    32. fmt.Printf("person = %+v", person)
    33. }
    34. // UnPerson 定义描述人的结构体,用于映射界面后的各字段
    35. type UnPerson struct {
    36. Name string `json:"name"`
    37. Age int `json:"age"`
    38. Sex bool `json:"sex"`
    39. Birthday string `json:"birthday"`
    40. Company string `json:"company"`
    41. Language []string `json:"language"`
    42. }

    GOROOT=D:\program_file_worker\go1.20 #gosetup
    GOPATH=D:\program_file_worker\go1.20\bin;C:\Users\Administrator\go #gosetup
    D:\program_file_worker\go1.20\bin\go.exe build -o C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_file__1_.exe D:\program_file\go_workspace\org.jd.data\file\OOPJSONFileToGrammarStructUnMarshal.go #gosetup
    C:\Users\Administrator\AppData\Local\Temp\GoLand\___go_build_org_jd_data_org_jd_data_file__1_.exe
    person = {Name:隔壁老王 Age:30 Sex:true Birthday:1992-12-12 Company:中国银行股份有限公司 Language:[Go从入门到精通 C语言从精通到放弃 Python语言修仙之道 零基础人
    生必修升仙指南]}
    Process finished with the exit code 0


     

  • 相关阅读:
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    第三方渠道管控,服务商能为您做什么
    Vue技术9.3
    Java多线程探究【四线程协作】
    C++ 实现读写锁的示例
    二蛋赠书二期:《Python机器学习项目实战》
    开发调试管理系统遇到的问题大全错误解决大全收集
    QT在安装后添加新组件【QT基础入门 环境搭建】
    使用OpenMMLab系列的开源库时,常用的脚本合集。
    常用vim操作
  • 原文地址:https://blog.csdn.net/u014635374/article/details/133924255