Create a file

 func createFile(a) {
	fileName := ""
	f, err := os.Create(fileName)
	defer f.Close()
	iferr ! =nil {
		// handle error
	} else {
		_, err := f.Write([]byte("Write content"))
		iferr ! =nil {
			// handle error}}}Copy the code

Read the file

// Read all files at once
func ReadAllOnce(path string) string {
	b, e := ioutil.ReadFile("d:/goTest/123.txt")
	ife ! =nil {
		fmt.Println("read file error")
		return ""
	}
	return string(b)
}

// Read all files at once
func ReadAllOnce2(path string) string {
    fi, err := os.Open(path)
    iferr ! =nil {
        panic(err)
    }
    defer fi.Close()
    fd, err := ioutil.ReadAll(fi)
    return string(fd)
}


// Read line by line
func ReadLineEachTime(path string) []string {
	cs := []string{}
	fi, err := os.Open(path)
	iferr ! =nil {
		fmt.Printf("Error: %s\n", err.Error())
		return cs
	}
	defer fi.Close()
	br := bufio.NewReader(fi)
	for {
		a, _, c := br.ReadLine()
		if c == io.EOF {
			break
		}
		cs = append(cs, string(a))
	}
	return cs
}
Copy the code

Write to file

Code 1:

func write2File(a) {
	f, err := os.OpenFile("filepath", os.O_WRONLY|os.O_TRUNC, 0600)
	defer f.Close()
	iferr ! =nil {
		// handle error
	} else {
    _, err := f.Write([]byte("What was written"))
    // Or use n3, err := f.riteString (" index \n")
		iferr ! =nil {
			// handle error}}}Copy the code

Code 2:

func check(e error) {
    ife ! =nil {
        panic(e)
    }
}
func main(a) {
    d1 := []byte("hello\ngo\n")
    err := ioutil.WriteFile("test.txt", d1, 0644)
    check(err)
}
Copy the code

Check whether a file or folder exists

// Check whether the given path file/folder exists
func Exists(path string) bool {
	_, err := os.Stat(path) // os.stat gets file information
	iferr ! =nil {
		if os.IsExist(err) {
			return true
		}
		return false
	}
	return true
}

// Check whether the given path is a folder
func IsDir(path string) bool {
	s, err := os.Stat(path)
	iferr ! =nil {
		return false
	}
	return s.IsDir()
}

// Check whether the given path is a file
func IsFile(path string) bool {
	return! IsDir(path) }Copy the code

Get the files in the directory

ReadDir reads all directories and files in a directory (current level, excluding subdirectories) using ioutil.ReadDir returns data types:

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)
}
Copy the code

Example:


func viewDir(a) {
    myfolder := `d:\go_workspace\`
    files, _ := ioutil.ReadDir(myfolder)
    for _, file := range files {
        if file.IsDir() {
            continue
        } else {
            fmt.Println(file.Name())
        }
    }
}
Copy the code

Use recursion to get the directory and all the files in the directory

func listFile(myfolder string) {
    files, _ := ioutil.ReadDir(myfolder)
    for _, file := range files {
        if file.IsDir() {
            listFile(myfolder + "/" + file.Name())
        } else {
            fmt.Println(myfolder + "/" + file.Name())
        }
    }
}
Copy the code

Gets the directory of the current project

func getPwd(a) {
    pwd, err := os.Getwd()
    iferr ! =nil {
        fmt.Println(err)
        os.Exit(1)
    }
    fmt.Println(pwd)
}
Copy the code

Gets all files in the folder and their sizes

func main(a) {
    dirname := "." + string(filepath.Separator)
    d, err := os.Open(dirname)
    iferr ! =nil {
        fmt.Println(err)
        os.Exit(1)}defer d.Close()
    fi, err := d.Readdir(- 1)
    iferr ! =nil {
        fmt.Println(err)
        os.Exit(1)}for _, fi := range fi {
        if fi.Mode().IsRegular() {
            fmt.Println(fi.Name(), fi.Size(), "bytes")}}}Copy the code

rename

// Rename the file
func main(a) {
    originalPath := "./test.txt"
    newPath := "test_new.txt"
    err := os.Rename(originalPath, newPath)
    iferr ! =nil {
        log.Fatal(err)
    }
}
// Rename the directory
func main(a) {
    originalPath := "test"
    newPath := "test_new"
    err := os.Rename(originalPath, newPath)
    iferr ! =nil {
        log.Fatal(err)
    }
}

Copy the code

Check the read and write permissions of a file

func main(a) {
    //Write permission
    file, err := os.OpenFile("./test.txt", os.O_WRONLY, 0666)
    iferr ! =nil {
        if os.IsPermission(err) {
            log.Println("Error: Write permission denied.")
        }
    }
    file.Close()

    //Read permission
    file, err = os.OpenFile("./test.txt", os.O_RDONLY, 0666)
    iferr ! =nil {
        if os.IsPermission(err) {
            log.Println("Error: Read permission denied.")
        }
    }
    file.Close()
}
Copy the code

Refer to the article

  • Golang file reads and writes