
Go语言入门心法(八): mysql驱动安装报错onnection failed
Go语言入门心法(十):Go语言操作MYSQL(CRUD)|事务处理
计算机文件是以硬盘为载体的信息存储集合,文件可以是文本,图片,程序等
文件通常被称为两类:
文本文件和二进制文件
通常我们对文件的操作有,创建文件,删除文件,读|写文件,修改文件等基础的操作,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
实例一: 读取文件或者递归读取文件夹下的子目录
- package main
-
- import (
- "fmt"
- "io/fs"
- "io/ioutil"
- "path/filepath"
- )
-
- /*
- 计算机文件是以硬盘为载体的信息存储集合,文件可以是文本,图片,程序等
- 文件通常被称为两类:
- 文本文件和二进制文件
- 通常我们对文件的操作有,创建文件,删除文件,读|写文件,修改文件等基础的操作,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
- */
- func main() {
- // 读取目录
- dir, err := ioutil.ReadDir("C:\\Users")
- if err != nil {
- fmt.Printf("系统异常: %s", err.Error())
- }
- for _, file := range dir {
- if file.IsDir() {
- fmt.Printf("读取到目录Users目录下的子目录: %s \n", file.Name())
- } else {
- fmt.Printf("读取到目录Users目录文件: %s \n", file.Name())
- }
-
- }
- println()
- println("通过os.FileIno接口可以获取到的信息如下:\n")
- println(`
- // 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)
- `)
- println()
- fmt.Printf("获取一个目录下的所有文件名(包括子文件夹内的所有文件),也就是递归遍历一个文件夹内所有的文件。\n Go语言提供了一个更加方便的操作函数,这个函数位于path/filePath库中" +
- "\n func Walk(root string,walkFn WalkFunc) error ")
-
- WalkDir("C:\\Windows\\Temp")
-
- }
-
- // WalkDir 打印指定目录下的所有文件,包括子目录
- func WalkDir(path string) {
- err := filepath.Walk(path, func(path string, file fs.FileInfo, err error) error {
- if file == nil {
- return err
- }
-
- if file.IsDir() {
- return nil
- }
- println(path)
- return nil
- })
- if err != nil {
- fmt.Printf("filepaht.Walk() returned %v \n", err)
- }
- }
运行效果:
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 othersMode() 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.logProcess finished with the exit code 0
- package main
-
- import (
- "fmt"
- "io/fs"
- "os"
- "path/filepath"
- )
-
- /*
- 创建目录与递归创建目录
- */
- func main() {
- println("===========================开始创建目录==================================\n")
- println()
- createDirAll("C:\\Users", "test\\dir1\\dir2")
- createDirAll("C:\\Windows\\Temp", "dir1\\dir2\\test")
- println()
- println("===========================创建目录结束==================================\n")
-
- println()
- println("=======================读取创建的目录==============================================")
- walkDir("C:\\Users\\test")
- walkDir("C:\\Windows\\Temp\\test")
- }
-
- // 创建目录
- func createDirAll(path string, dirName string) {
- dirPath := path + "\\" + dirName
- // 0777也可以os.ModePerm
- fmt.Println("Create Dir => " + dirPath)
- err := os.MkdirAll(dirPath, 0777)
- if err != nil {
- fmt.Printf("文件创建失败: %s \n", dirPath)
- } else {
- fmt.Printf("文件创建成功: %s", dirPath)
- fmt.Println("Create Dir => " + dirPath)
- }
- os.Chmod(dirPath, 0777)
-
- }
-
- // walkDir 打印指定目录下的所有文件,包括子目录
- func walkDir(path string) {
- err := filepath.Walk(path, func(path string, file fs.FileInfo, err error) error {
- if file == nil {
- return err
- }
-
- if file.IsDir() {
- println("目录: ", path)
- return nil
- }
- println("文件: ", path)
- return nil
- })
- if err != nil {
- fmt.Printf("文件或者目录不存在: %v \n", err.Error())
- }
- }
运行效果:
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\testProcess finished with the exit code 0
删除文件目录:
(1)删除文件目录可以使用接口: func Remove(name string) error ;Remove删除name指定的文件或目录。此接口只能删除空文件夹,
如果文件夹不为空,则会删除失败,返回"文件夹为非空"错误
(2)对于文件夹不为空的情况,可以使用RemoveAll(path string) error 这个接口
- package main
-
- import (
- "fmt"
- "os"
- )
-
- /*
- 删除文件目录:
- (1)删除文件目录可以使用接口: func Remove(name string) error ;Remove删除name指定的文件或目录。此接口只能删除空文件夹,
- 如果文件夹不为空,则会删除失败,返回"文件夹为非空"错误
- (2)对于文件夹不为空的情况,可以使用RemoveAll(path string) error 这个接口
- */
- func main() {
- println("====================================删除空目录开始==============================")
- deleteEmptyDir("D:\\program files\\test")
- println("====================================删除空目录结束==============================")
- println()
- println()
- println("====================================删除非空目录开始==============================")
- deleteNotEmpty("D:\\program files\\test")
- println("====================================删除非空目录结束==============================")
- }
-
- // 删除空目录
- func deleteEmptyDir(dirPath string) {
- fmt.Println("Delete Dir => " + dirPath)
- err := os.Remove(dirPath)
-
- if err != nil {
- fmt.Println(err)
- } else {
- fmt.Println("Delete Success!")
- }
- }
-
- // 删除非空目录
- func deleteNotEmpty(dirPath string) {
- fmt.Println("Delete Dir => " + dirPath)
- err := os.RemoveAll(dirPath)
-
- if err != nil {
- fmt.Println(err)
- } else {
- fmt.Println("Deletes Success!")
- }
-
- }
运行效果:
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
- package main
-
- import (
- "fmt"
- "os"
- )
-
- /*
- 打开及读取文件
- */
- func main() {
- var filePath string = "C:\\Windows\\Temp\\test.txt"
- openExistElseCreate(filePath)
- println()
- readFile(filePath)
- }
-
- // 以只读打开一个文件,如果文件不存在,则创建一个文件
- func openExistElseCreate(filePath string) {
- file, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE, 0766)
- if err != nil {
- fmt.Println(err)
- } else {
- fmt.Println(file)
- file.Close()
- }
- println()
- fmt.Println("os关于系统文件相关常量定义")
- println(`
- 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.
- )
- `)
- }
-
- func readFile(pathFile string) {
- // 读取文件内容
- file, err := os.Open(pathFile)
- if err != nil {
- fmt.Println(err)
- return
- }
- // 创建byte的slice用于接收文件读取数据
- buf := make([]byte, 1024)
- println()
- println()
- fmt.Println("以下是文件内容:")
-
- // 循环读取
- for {
- // Read函数会改变文件当前偏移量
- len, _ := file.Read(buf)
- // 读取字节数为0时跳出循环
- if len == 0 {
- break
- }
- fmt.Println(string(buf))
- }
- defer file.Close()
- }
运行效果:
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;
这个接口可以指定从指定文件的位置开始读取。
- package main
-
- import (
- "fmt"
- "os"
- )
-
- /*
- 读取文件函数认知升维:
- (1)Read与ReadAt函数的区别:前者从文件当前偏移量处开始读取,且会改变文件当前的偏移量;而后者从off指定的位置开始读取,
- 且不会改变文件当前偏移量
- (2)当遇到特别大的文件,并且只需要读取文件最后部分的内容时,Read接口就不能满足我们需要了,这时就可以使用另外一个读取接口ReadAt;
- 这个接口可以指定从指定文件的位置开始读取。
- */
- func main() {
- pathFile := "C:\\Windows\\Temp\\readAt.txt"
- readFileByLocation(pathFile)
- }
-
- func readFileByLocation(path string) {
- // 读取文件内容
- file, err := os.Open(path)
- if err != nil {
- fmt.Println(err)
- return
- }
- // 创建byte的slice用于接收文件读取数据
- buf := make([]byte, 1024)
- fmt.Println("以下是文件的内容: ")
- // 读取偏移9字节的数据
- _, _ = file.ReadAt(buf, 9)
- fmt.Println(string(buf))
- _ = file.Close()
- }
运行效果:
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的错误
- package main
-
- import (
- "fmt"
- "os"
- "strconv"
- )
-
- /*
- 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的错误
- */
- func main() {
- pathFile := "C:\\Windows\\Temp\\11.txt"
- writeData(pathFile)
- println()
- writeDataAtLocation("C:\\Windows\\Temp\\Write.txt")
- }
-
- // 从文件开头写入数据
- func writeData(path string) {
- file, err := os.Create(path)
- if err != nil {
- fmt.Println(err)
- return
- }
- data := "你好,欢迎来到go语言操作文件相关的方法\r\n"
- for i := 0; i < 10; i++ {
- // 写入byte的slice数据
- file.Write([]byte(data))
- }
- println("数据写入成功")
- defer file.Close()
-
- println()
- println()
- println("=============指定偏移量写入数据====================")
- println()
- }
-
- // 从指定的位置开始写入数据,这个指定的位置是相对于开始位置
- func writeDataAtLocation(path string) {
- file, err := os.Create(path)
-
- if err != nil {
- fmt.Println(err)
- }
- for i := 0; i < 5; i++ {
- // 按指定偏移量写入数据
- ix := i * 64
- file.WriteAt([]byte("这是指定偏移位置写入到数据"+strconv.Itoa(i)+"\r\n"), int64(ix))
- }
- println("从指定的偏移位置,写入数据成功!")
- defer file.Close()
- }
运行效果:
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
删除文件的接口与删除目录的接口一致
- package main
-
- import (
- "fmt"
- "os"
- )
-
- /*
- 删除文件目录:
- (1)删除文件目录可以使用接口: func Remove(name string) error ;Remove删除name指定的文件或目录。此接口只能删除空文件夹,
- 如果文件夹不为空,则会删除失败,返回"文件夹为非空"错误
- (2)对于文件夹不为空的情况,可以使用RemoveAll(path string) error 这个接口
- */
- func main() {
- println("====================================删除空目录开始==============================")
- deletePathFile("C:\\Windows\\Temp\\Write.txt")
- println("====================================删除空目录结束==============================")
- println()
- println()
- println("====================================删除非空目录下的所有文件开始==============================")
- deleteDirLowerAllFiles("C:\\Windows\\Temp\\")
- println("====================================删除非空目录下的所有文件结束==============================")
- }
-
- // 删除指定路径的文件
- func deletePathFile(dirPath string) {
- fmt.Println("Delete Dir => " + dirPath)
- err := os.Remove(dirPath)
-
- if err != nil {
- fmt.Println(err)
- } else {
- fmt.Println("Delete Success!")
- }
- }
-
- // 删除非空目录下的所有文件
- func deleteDirLowerAllFiles(dirPath string) {
- fmt.Println("Delete Dir => " + dirPath)
- err := os.RemoveAll(dirPath)
-
- if err != nil {
- fmt.Println(err)
- } else {
- fmt.Println("Deletes Success!")
- }
-
- }
运行效果:
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(JavaScript Object Notation,JS对象简谱)是一种轻量级数据交换格式,基本上所有的语言都支持JSON数据编码和解码;
编码JSON,即从其他的数据类型编码成JSON字符串,这个过程使用如下接口
func Marshal(v interface{}) ([]byte, error);
为了使JSON字符串更加直观,可以使用MarshalIndent函数进行输出格式化操作
func MarshalIndent(v interface{},prefix,indent string) ([]byte,error);该函数会使用缩进将输出格式化
- package main
-
- import (
- "encoding/json"
- "fmt"
- )
-
- /*
- 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);该函数会使用缩进将输出格式化
- */
- func main() {
-
- // 创建一个map
- m := make(map[string]interface{}, 6)
- m["name"] = "王二麻子"
- m["age"] = 24
- m["sex"] = true
- m["birthday"] = "2023-01-012"
- m["company"] = "Go重构有限公司"
- m["language"] = []string{"Go", "PHP", "Python"}
-
- // 编码为JSON
- result, _ := json.Marshal(m)
- resultFormat, _ := json.MarshalIndent(m, "", " ")
- fmt.Println("result = ", string(result))
- println()
- fmt.Println("resultFormat = ", string(resultFormat))
-
- }
运行效果:
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
- package main
-
- import (
- "encoding/json"
- "fmt"
- )
-
- /*
- 结构体类型数据解码为JSON的互操作
- */
- func main() {
- // 定义一个结构体变量
-
- person := Person{"隔壁老王", 30, true, "1992-12-12", "中国银行股份有限公司",
- []string{"Go从入门到精通", "C语言从精通到放弃", "Python语言大仙", "零基础人生必修升仙指南"}}
- result, err := json.Marshal(person)
- if err != nil {
- fmt.Println(err)
- return
- }
- println("result : ", string(result))
-
- result, err = json.MarshalIndent(person, "", " ")
- // 格式化输出json文件
- fmt.Println("resultIndent : ", string(result))
- }
-
- // Person 定义描述人的结构体
- type Person struct {
- Name string `json:"name"`
- Age int `json:"age"`
- Sex bool `json:"sex"`
- Birthday string `json:"birthday"`
- Company string `json:"company"`
- Language []string `json:"language"`
- }
运行效果:
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
- package main
-
- import (
- "fmt"
- "github.com/goccy/go-json"
- )
-
- /*
- Json字符串转换为Map类型的数据
- */
- func main() {
-
- jsonStr := `
- {
- "name": "隔壁老王",
- "age": 30,
- "sex": true,
- "birthday": "1992-12-12",
- "company": "中国银行股份有限公司",
- "language": [
- "Go从入门到精通",
- "C语言从精通到放弃",
- "Python语言修仙之道",
- "零基础人生必修升仙指南"
- ]
- }
- `
- // 创建一个Map类型的变量
- mapResult := make(map[string]interface{}, 6)
- // json字符串界面为map类型数据
- err := json.Unmarshal([]byte(jsonStr), &mapResult)
- if err != nil {
- fmt.Println(err)
- }
- fmt.Println(" mapResult = ", mapResult)
- println()
- // 类型断言
- for key, value := range mapResult {
- switch data := value.(type) {
- case string:
- fmt.Printf("map[%s]的值类型为 string,value = %s \n", key, data)
-
- case float64:
- fmt.Printf("map[%s]的值类型为 int,value = %f \n", key, data)
-
- case bool:
- fmt.Printf("map[%s]的值类型为 bool,value = %t \n", key, data)
-
- case []string:
- fmt.Printf("map[%s]的值类型为 []string,value = %v \n", key, data)
-
- case []interface{}:
- fmt.Printf("map[%s]的值类型为 []interface,value = %v \n", key, data)
-
- }
-
- }
- }
运行效果:
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 = trueProcess finished with the exit code 0
- package main
-
- import (
- "encoding/json"
- "fmt"
- )
-
- /*
- json字符串界面为struct结构体类型的数据
- */
- func main() {
- jsonStr := `
- {
- "name": "隔壁老王",
- "age": 30,
- "sex": true,
- "birthday": "1992-12-12",
- "company": "中国银行股份有限公司",
- "language": [
- "Go从入门到精通",
- "C语言从精通到放弃",
- "Python语言修仙之道",
- "零基础人生必修升仙指南"
- ]
- }
- `
- // 实例化结构体对象
- var person UnPerson
- // 解码字符串
- err := json.Unmarshal([]byte(jsonStr), &person)
- if err != nil {
- fmt.Println(err)
- }
- fmt.Printf("person = %+v", person)
- }
-
- // UnPerson 定义描述人的结构体,用于映射界面后的各字段
- type UnPerson struct {
- Name string `json:"name"`
- Age int `json:"age"`
- Sex bool `json:"sex"`
- Birthday string `json:"birthday"`
- Company string `json:"company"`
- Language []string `json:"language"`
- }
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