Package Mainimport ("Bufio" "FMT" "io" "io/ioutil" "OS")//Use Ioutil read-write file func ioutil_method (path string) {//write file//writes only bytes, So you need to convert the content: = []byte ("Life half は Shi Fang がないでできてる, remnant りの half cent は, Kaesa りたい") ioutil. WriteFile ("A.txt", Content, 0644)//Read file, err: = Ioutil. ReadFile (path) if err!=nil{fmt. PRINTLN (ERR) return}//The file here must be prefixed with a string, otherwise an int array of FMT will be printed. Println (string file)//Life half は Shi Fang がないでできてる, remnant りの half cent は, Kaesa りたい}//Use the OS to read the file func os_method (path string) {//write file F, Err:=os. Create ("B.txt") defer f.close () if err!=nil{fmt. PRINTLN (ERR) return}//can use F. WriteString write a string, or you can use F. Write writes Byte f.writestring ("Life half cent は Shi Fang がないでできてる, remnant りの half cent は, Kaesa りたい") F.write ([]byte ("Life half cent は Shi Fang がないでできてる, remnant りの half cent は, Kaesa りたい"))//Read file F, Err=os. Open ("B.txt") if err!=nil{fmt. PRINTLN (err) Return}chunks: = made ([]byte, 1024x768) BUF: = Make ([]byte, 1024x768) for {//Read file must create a buffer to read the contents of F into the BUF, Returns an n indicating the length of the read, and the ERR error message N, err: = F.read (BUF) if Err!=nil && Err!=io. Eof{fmt. PRINTLN (err) return}if 0 = = n{break}//Add the Read bytes to the chunks inside chunks = append (chunks, buf[: n] ...)} The read chunks turns into stringfmt. Println (String (chunks))//Life half cent は Shi Fang がないでできてる, remnant りの half cent は, kaesa りたい life half cent は Shi Fang がないでできてる, remnant りの half cent は, Kaesa りたい}//use Bufio Read file func bufio_method () {F,_:=os. Open ("A.txt") defer f.close () chunks: = Make ([]byte, 1024x768) BUF: = Make ([]byte, 1024x768) r: = Bufio. Newreader (f) for {//through BUFIO. Newreader processed F, or R, can also call Readn, err: = R.read (BUF) if Err!=nil && Err!=io. Eof{fmt. PRINTLN (err)}if 0 = = N{break}chunks = Append (chunks, buf[: n] ...)} Fmt. Println (String (chunks))//Life half cent は Shi Fang がないでできてる, remnant りの half cent は, Kaesa りたい}//use Ioutil. ReadAll Read file func Readall_method () {F, _:=os. Open ("A.txt") defer f.close () file, _: = Ioutil. ReadAll (f) fmt. Println (string file)//Life half は Shi Fang がないでできてる, remnant りの half cent は, Kaesa りたい}func main () {Ioutil_method ("a.txt") Os_method ("B.txt") Bufio_ Method () Readall_method ()}//uses Ioutil. The ReadAll function reads the file best
Several ways to read and write files in the Go language