Go language basic reading and writing tool ioutil package

Do you think it is very troublesome to read and write files under the os package? First, you need to open the file, then read the file, and then use the []byte array to read and write bit by bit. Let me introduce you to a very The easy-to-use method, the iotuil package, there are not many methods here, but they are all very convenient methods. They are all packaged, and the files do not need to be opened, just use them directly.

The ioUtil package
ReadFile(filename)-->[]byte data *****
reads all the content in the specified file, returns a slice, err returns EOF
WriteFile(filename, [] byte data, FileMode) *****
Write data to the specified file,
ReadAll() reads the data, and err returns nil instead of EOF after reading

package main

import (
   "io/ioutil"
   "fmt"
   "strings"
)

func main()  {
   fileName:="c:\\liu\\pro\\aa.txt"
   bs, err:=ioutil.ReadFile(fileName)
   fmt.Println(err)//<nil>
   fmt.Println(bs)
   fmt.Println(string(bs))

   fileName2:="C:\\Ruby\\pro\\aoo.txt"
   s1:="HelloWorld"
   err=ioutil.WriteFile(fileName2,[]byte(s1),0777)
   fmt.Println(err)

   s2:="qwertyuiopasdfghjklzxcvbnm"
   reader1:=strings.NewReader(s2)//
   //file,err:=os.Open("")//Read()
   bs2,_:=ioutil.ReadAll(reader1)
   fmt.Println(string(bs2))
}

ReadDir(dirname)-->[]FileInfo

Get the sub-content under the specified directory, only one level


package main import ( "io/ioutil" "fmt" ) func main () { /* readDir(dirname)-->[] FileInfo gets the contents of the corresponding directory, only one layer. */ dirName:= "C:\\Ruby\\pro" fileInfos , _:=ioutil.ReadDir(dirName) fmt.Println(len(fileInfos)) for i , fi:= range fileInfos{ fmt.Printf( "The first %d sub-contents: \n" , i+ 1 ) fmt.Println( "\tName:" , fi.Name()) fmt.Println( "Is \t a directory:" , fi.IsDir()) }}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325942710&siteId=291194637