• Go的IO操作


    一, 文件信息

    1, FileInfo接口

    文件信息包括文件名、文件大小、修改权限、修改时间等。

    Go的文件信息接口属性定义如下。

    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() interface{}   // underlying data source (can return nil)
    }
    

    fileStat结构体(文件信息)定义如下所示:

    type fileStat struct {
       name    string
       size    int64
       mode    FileMode
       modTime time.Time
       sys     syscall.Stat_t
    }
    

    常用方法如下:

    ![image-20200407222501541](/Users/jack_zhou/Library/Application Support/typora-user-images/image-20200407222501541.png)

    想看一个文件,必须知道文件的路径

    ![image-20200407222924788](/Users/jack_zhou/Library/Application Support/typora-user-images/image-20200407222924788.png)

    比如这一张照片。

    路径分为绝对路径和相对路径

    绝对路径:/Users/jack_zhou/Pictures/photo/相机/20160206_143218.jpg

    相对路径:相对这个工程路径为../Pictures/photo/相机/20160206_143218.jpg

    package main
    
    import (
    	"fmt"
    	"os"
    )
    
    func printmessage(path string) {
    	if fileinfo, err := os.Stat(path); err != nil {
    		fmt.Println("读取出错%s", err.Error())
    	} else {
    		fmt.Printf("数据类型为:%T 
    ", fileinfo)
    		fmt.Printf("文件名为:%s 
    ", fileinfo.Name())
    		fmt.Println("是否为目录:", fileinfo.IsDir())
    		fmt.Printf("文件大小为:%d 
    ", fileinfo.Size())
    		fmt.Printf("文件权限为:%s 
    ", fileinfo.Mode())
    		fmt.Printf("文件最后修改时间:%s 
    ", fileinfo.ModTime())
    	}
    
    }
    
    func main() {
    	// 绝对路径/Users/jack_zhou/Pictures/photo/相机/20160206_143218.jpg
    	path := "/Users/jack_zhou/Pictures/photo/相机/20160206_143218.jpg"
    	printmessage(path)
    }
    
    

    ![image-20200407224838108](/Users/jack_zhou/Library/Application Support/typora-user-images/image-20200407224838108.png)

    2, 文件路径

    方法 作用
    filepath.IsAbs() 判断是否为绝对路径
    filepath.Rel() 获取相对路径
    filepath.Abs() 获取绝对路径
    path.Join() 拼接路径
    package main
    
    import (
       "fmt"
       "path/filepath"
    )
    
    func printmessage(path string) {
       filepath_picture := path
       fmt.Println(filepath.Abs(filepath_picture))
       fmt.Println(filepath.Rel("/Users/jack_zhou/", filepath_picture))
       fmt.Println(filepath.IsAbs(filepath_picture))
    }
    
    func main() {
       // 绝对路径/Users/jack_zhou/Pictures/photo/相机/20160206_143218.jpg
       path := "/Users/jack_zhou/Pictures/photo/相机/20160206_143218.jpg"
       printmessage(path)
    }
    

    二, 文件操作

    1, 创建目录

    os.MKdir()

    2, 递归创建目录

    os.MKdirAll()

    package main
    
    import (
       "fmt"
       "os"
    )
    
    func main() {
       filenames := "./test"
       err := os.Mkdir(filenames, os.ModePerm)
       if err != nil {
          fmt.Println("err:", err.Error())
       } else {
          fmt.Printf("%s 目录创建成功", filenames)
       }
       filenamess := "./test/abs/xxx"
       err = os.MkdirAll(filenamess, os.ModePerm)
       if err != nil {
          fmt.Println("err:", err.Error())
       } else {
          fmt.Printf("%s 目录创建成功!
    ", filenamess)
       }
    }
    

    3, 创建文件

    os.Create() 如果文件存在,会将其覆盖

    4, 打开关闭文件

    os.Open()实际调用os.OpenFile(filename, mode, perm)

    mode可以存在多个方式,用“|”分开

    文件不存在时创建文件需要指定权限。

    os.Close()

    package main
    
    import (
       "fmt"
       "os"
    )
    
    func main() {
       filenames := "./test/a.txt"
       file, err := os.Open(filenames)
    
       if err != nil {
          fmt.Println("err:", err.Error())
       } else {
          fmt.Printf("%s打开成功, %v", filenames, file)
       }
       // 读写方式打开
       file2, err := os.OpenFile(filenames, os.O_CREATE|os.O_RDWR, os.ModePerm)
       if err != nil {
          fmt.Println("err:", err.Error())
       } else {
          fmt.Printf("%s 打开成功 %v", filenames, file2)
       }
       file.Close()
       file2.Close()
    }
    

    5, 删除文件

    os.Remove() 删除文件或者空目录

    os.RemoveAll()删除所有的路径和它包含的任意子节点

    三, 读写和复制文件

    1,读文件

    os.Open(filename)

    file.Read() 从文件中开始读取数据,返回值n是实际读取的字节数。如果读取到文件末尾,n为0或err为io.EOF

    package main
    
    import (
       "fmt"
       "io"
       "os"
    )
    
    func main() {
       filenames := "./test/a.txt"
       file, err := os.Open(filenames)
       if err != nil {
          fmt.Println("打开错误", err.Error())
       } else {
          bs := make([]byte, 1024*8, 1024*8)
          n := -1
          for {
             n, err = file.Read(bs)
             if n == 0 || err == io.EOF {
                fmt.Println("读取结束")
                break
             }
             fmt.Println(string((bs[:n])))
          }
       }
    }
    

    2,写文件

    ① 打开或创建文件

    os.OpenFile()

    ② 写入文件

    file.Write([]byte)-->n,err

    file.WriteString(string)-->n,err

    ③ 关闭文件

    file.close()

    package main
    
    import (
       "fmt"
       "os"
    )
    
    func main() {
       file, err := os.Open("./file/abc.txt", os.O_RDWR|os.O_CREATE, os.ModePerm)
    
       if err != nil {
          fmt.Println("打开文件异常", err.Error())
       } else {
          defer file.Close()
          n, err := file.Write([]byte("abcvdkjohkhkj"))
          if err != nil {
             fmt.Println("写入异常", err.Error())
          } else {
             fmt.Println("写入成功")
          }
          n, err = file.WriteString("中文")
          if err != nil {
             fmt.Println("写入异常", err.Error())
          } else {
             fmt.Println("写入ok:", n)
          }
       }
    }
    

    3, 复制文件

    newFile, err := os.Create(filemeta.Location)
    if err != nil {
       fmt.Printf("Filed to create file")
       return
    }
    defer newFile.Close()
    filemeta.FileSize, err = io.Copy(newFile, file)  // 第一个返回值是文件的大小
    

    还可以

    err := ioutil.WriteFile(filename_path, file, os.ModePerm)

    四, ioutil包

    方法 作用
    ReadFile() 读取文件中的所有的数据,返回读取的字节数组
    WriteFile() 向指定文件写入数据,如果文件不存在,创建文件,写入数据之前会清空文件
    ReadDir() 读取一个目录下的子内容(子文件和子目录名称),但是仅有一层
    TempDir() 在当前目录下,创建一个以指定字符串为名称前缀的临时文件夹,并返回文件夹路径
    TempFile() 在当前目录下,创建一个以指定字符串为名称前缀的文件,并以读写模式打开文件,并返回os.File指针对象。
  • 相关阅读:
    团队开发16
    小工具集合Alpha版使用说明
    团队开发15
    《编写有效用例》读后感3
    《编写有效用例》读后感2
    《编写有效用例》读后感1
    《架构漫谈》读后感3
    《架构漫谈》读后感2
    《架构漫谈》读后感1
    SOA设计与应用
  • 原文地址:https://www.cnblogs.com/zhoulixiansen/p/12669796.html
Copyright © 2020-2023  润新知