Go IO operations

First, the file information

1, FileInfo Interface

File information including file name, file size, modification permissions, modification time.

Go file information interface attributes are defined as follows.

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 structure (file information) is defined as follows:

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

Common methods are as follows:

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

Want to see a file, you must know the path to the file

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

For example, this photo.

Path is divided into absolute and relative paths

Absolute path: / Users / jack_zhou / Pictures / photo / camera /20160206_143218.jpg

Relative path: the path is relative to this project ../Pictures/photo/ camera /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 \n", fileinfo)
		fmt.Printf("文件名为:%s \n", fileinfo.Name())
		fmt.Println("是否为目录:", fileinfo.IsDir())
		fmt.Printf("文件大小为:%d \n", fileinfo.Size())
		fmt.Printf("文件权限为:%s \n", fileinfo.Mode())
		fmt.Printf("文件最后修改时间:%s \n", 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, the file path

method effect
filepath.IsAbs() Determine whether the absolute path
filepath.Rel() Get the relative path
filepath.Abs() Gets the absolute path
path.Join() Stitching path
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)
}

Second, file operations

1. Create a directory

os.MKdir()

2, create directories recursively

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 目录创建成功!\n", filenamess)
   }
}

3, create a file

os.Create() If the file exists, it will be covered

4, opening and closing files

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

mode can exist in multiple ways, using | to separate ""

Create a file you need to specify permissions file does not exist.

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, delete files

os.Remove() Delete files or empty directories

os.RemoveAll()Remove all paths and any child nodes it contains

Third, read and write and copy files

1, read file

os.Open(filename)

file.Read()Reads data from the file and returns the value n is the number of bytes actually read. If the end of the file is read, n is 0 or err is 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, write file

① open or create file

os.OpenFile()

② write to file

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

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

③ close the file

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, copy the files

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)  // 第一个返回值是文件的大小

still alright

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

Four, ioutil package

method effect
ReadFile() All of the data file is read, the read returns a byte array
WriteFile() Write data to the specified file, if the file does not exist, create a file, the file will be cleared before writing data
ReadDir() Read sub-content (sub-files and subdirectories name) in a directory, but only one
TempDir() In the current directory, create a string to specify the name prefix of the temporary folder, and returns the folder path
TempFile() In the current directory, create a file with the specified string as a name prefix, and open the file in read-write mode and return os.File pointer object.

Guess you like

Origin www.cnblogs.com/zhoulixiansen/p/12669796.html