Automated management of files and folders
Read and write files
read file
Using ioutil Readfile reads directly from the file into [] byte
Package name: io/ioutil
Prototype: func ReadFile(filename string) ([]byte, error)
Function: ReadFile reads data from the file specified by filename and returns the contents of the file. The err returned by a successful call is nil instead of EOF. Because this function is defined as reading the entire file, it will not treat the EOF returned by reading as an error that should be reported.
Return: [] byte, error
Example:
package main import ( "fmt" "io/ioutil" ) func Read(path string) string { bs, err := ioutil.ReadFile(path) if err != nil { fmt.Println("Read Fail", err) } return string(bs) } func main() { path := `F:\blog\test.txt` result := Read(path) fmt.Println(result) }
First read from the file to the file, then read from the file to the buf, and the buf is appended to the final [] byte
Package name: os
Prototype: func Open(name string) (file *File, err error)
Function: Open opens a file for reading. If the operation is successful, the method of the returned file object can be used to read data; The corresponding file descriptor has O_RDONLY mode. If an error occurs, the underlying type of the error is * PathError.
Return: * File, error
Package name: os
Prototype: func (f *File) Read(b []byte) (n int, err error)
Function: the Read method reads up to len(b) bytes of data from f and writes it to B. It returns the number of bytes Read and any errors that may be encountered. The file termination flag reads 0 bytes and the return value err is Io EOF.
Return: int, error
Package name: os
Prototype: func (f *File) Close() error
Function: Close closes the file f so that the file cannot be used for reading and writing. It returns possible errors.
Return: error
Package name: io
Prototype: VAR EOF = errors New("EOF")
Function: io EOF is a variable in the IO package, indicating an error at the end of the file. When no more input can be obtained, the Read method returns EOF. When the function reaches the end of the input normally, it should return EOF.
Example:
package main import ( "fmt" "io" "os" ) func Read(path string) string { // Get a file f, err := os.Open(path) if err != nil { fmt.Println("Read Fail") return "" } // Read file into buffer defer f.Close() var chunk []byte buf := make([]byte, 1024) for { // Read from file to buf n, err := f.Read(buf) if err != nil && err != io.EOF { fmt.Println("Read Buf Fail", err) return "" } // Description end of reading if n == 0 { break } // Read into the final buffer chunk = append(chunk, buf[:n]...) } return string(chunk) } func main() { path := `F:\blog\test.txt` result := Read(path) fmt.Println(result) }
First read the file from the file, then read the buf from the Reader in the file to Reader, and finally append the buf to [] byte
Package name: bufio
Prototype: func NewReader(rd io.Reader) *Reader
Function: NewReader creates a * Reader with default size buffer and read from r.
Return: * Reader
Package name: bufio
Prototype: func (b *Reader) Read(p []byte) (n int, err error)
Function: Read reads data and writes p. This method returns the number of bytes written to p. This method can call the Read method of the lower Reader interface at most once in one call, so the return value n may be less than len(p). When the reading reaches the end, the return value n will be 0 and err will be io EOF.
Return: int, error
Package name: os
Prototype: func (f *File) Close() error
Function: Close closes the file f so that the file cannot be used for reading and writing. It returns possible errors.
Return: err
Example:
package main import ( "bufio" "fmt" "io" "os" ) func Read(path string) string { f, err := os.Open(path) if err != nil { panic(err) } defer f.Close() r := bufio.NewReader(f) var chunks []byte buf := make([]byte, 1024) for { n, err := r.Read(buf) if err != nil && err != io.EOF { panic(err) } if n == 0 { break } chunks = append(chunks, buf...) } return string(chunks) } func main() { path := `F:\blog\test.txt` result := Read(path) fmt.Println(result) }
Read it into file, and then use ioutil to directly read the file into [] byte
Package name: io/ioutil
Prototype: func ReadAll(r io.Reader) ([]byte, error)
Function: ReadAll reads data from R to EOF or encounters error, and returns the read data and encountered error. The err returned by a successful call is nil instead of EOF. Because this function is defined as reading r until EOF, it will not treat the EOF returned by reading as an error that should be reported.
Return: [] byte, error
Example:
package main import ( "fmt" "io/ioutil" "os" ) func Read(path string) string { f, err := os.Open(path) if err != nil { fmt.Println("Read File Fail", err) return "" } defer f.Close() fd, err := ioutil.ReadAll(f) if err != nil { fmt.Println("Read To fd Fail", err) return "" } return string(fd) } func main() { path := `F:\blog\test.txt` result := Read(path) fmt.Println(result) }
write file
Use io Writestring write file
Package name: os
Prototype: func Stat(name string) (fi FileInfo, err error)
Function: Stat returns a FileInfo describing the file object specified by name. If the specified file object is a symbolic link, the returned FileInfo describes the information of the file pointed to by the symbolic link, and this function will try to jump to the link. If there is an error, the returned error value is of type * PathError.
Return: FileInfo, error
Package name: os
Prototype: func IsNotExist(err error) bool
Function: returns a Boolean value indicating whether the error indicates that a file or directory does not exist. ErrNotExist and some system call errors will make it return true.
Return: bool
Package name: os
Prototype: func OpenFile(name string, flag int, perm FileMode) (file *File, err error)
Function: OpenFile is a more general file opening function. Most callers apply Open or Create instead of this function. It will Open the file with the specified name using the specified options (such as O_RDONLY, etc.) and the specified mode (such as 0666, etc.). If the operation is successful, the returned file object can be used for I/O. If an error occurs, the underlying type of the error is * PathError.
Return: * File, error
Package name: os
Prototype: func Create(name string) (file *File, err error)
Function: Create creates a file named name using the mode 0666 (anyone can read and write, not executable). If the file already exists, it will be truncated (empty file). If successful, the returned file object can be used for I/O; The corresponding file descriptor has O_RDWR mode. If an error occurs, the underlying type of the error is * PathError.
Return: * File, error
Package name: os
Prototype: func (f *File) WriteString(s string) (ret int, err error)
Function: WriteString writes s string to file. It returns the number of bytes written and any errors that may be encountered.
Return: int, error
Example:
package main import ( "fmt" "io" "os" ) func CheckFileExist(fileName string) bool { _, err := os.Stat(fileName) return !os.IsNotExist(err) } func Write(path string, text string) { var f *os.File var err error if CheckFileExist(path) { // File exists // Open file f, err = os.OpenFile(path, os.O_APPEND, 0666) if err != nil{ fmt.Println("File Open Fail", err) return } }else { // file does not exist // create a file f, err = os.Create(path) if err != nil { fmt.Println("File Create Fail") return } } // Write the file in n, err1 := io.WriteString(f, text) if err1 != nil { fmt.Println("Write Error", err1) return } fmt.Println("The number of bytes written is:", n) } func main() { path := `F:\blog\test.txt` Write(path, "Golang\n") }
Use ioutil WriteFile write file
Package name: io/ioutil
Prototype: func WriteFile(filename string, data []byte, perm os.FileMode) error
Function: writes data to the file specified by filename. If the file does not exist, the file will be created according to the given permissions, otherwise the file will be emptied before writing data.
Return: error
Example:
package main import ( "fmt" "io/ioutil" ) func Write(path string, text string) { var d = []byte(text) err := ioutil.WriteFile(path, d, 0666) if err != nil { fmt.Println("Write Fail") } fmt.Println("Write Success") } func main() { path := `F:\blog\test.txt` Write(path, "Golang\n") }
Use File(Write,WriteString) to write files
Package name: os
Prototype: func (f *File) Write(b []byte) (n int, err error)
Function: Write writes len(b) byte data to the file. It returns the number of bytes written and any errors that may be encountered. If the return value is n= len(b), this method will return a non nil error.
Return: int, error
Package name: os
Prototype: func (f *File) WriteString(s string) (ret int, err error)
Function: WriteString is similar to Write, but accepts a string parameter.
Return: error
Package name: os
Prototype: func (f *File) Sync() (err error)
Function: Sync delivers the current content of the file for stable storage. Generally speaking, this means that the copy of the recently written data of the file system in memory is refreshed to the hard disk for stable storage.
Return: error
Example:
package main import ( "fmt" "os" ) func Write(path string, text string) { // create a file f, err := os.Create(path) if err != nil { fmt.Println("Create File Fail") } defer f.Close() // Write file (byte array) n1, _ := f.Write([]byte(text)) fmt.Printf("write in %d Bytes", n1) // Write file (byte array) n2, _ := f.WriteString(text) fmt.Printf("write in %d Bytes", n2) f.Sync() } func main() { path := `F:\blog\test.txt` Write(path, "Golang\n") }
Use bufio Newwriter writes files
Package name: bufio
Prototype: func NewWriter(w io.Writer) *Writer
Function: NewWriter creates a * Writer with default size buffer and write w.
Return: * Writer
Package name: bufio
Prototype: func (b *Writer) WriteString(s string) (int, error)
Function: WriteString writes a string. Returns the number of bytes written. If the return value NN < len (s), an error is also returned indicating the reason.
Return: int, error
Package name: bufio
Prototype: func (b *Writer) Flush() error
Function: Flush method writes the data in the buffer to the IO of the lower layer Writer interface.
Return: error
Example:
package main import ( "bufio" "fmt" "os" ) func Write(path string, text string) { // create a file f, err := os.Create(path) if err != nil { fmt.Println("Create File Fail") } // Create a new Writer object w := bufio.NewWriter(f) n, _ := w.WriteString(text) fmt.Printf("write in %d Bytes", n) w.Flush() f.Close() } func main() { path := `F:\blog\test.txt` Write(path, "Golang\n") }