In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces "how to read and write files in Go language". In the daily operation, I believe that many people have doubts about how to read and write files in GE language. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to read and write files in Go language". Next, please follow the editor to study!
1.func Copy (dst Writer, src Reader) (written int64, err error) this function reads and copies from one file to another, all the way to the EOF that reads the file, so it does not return an io.EOF error. The argument is to write to the target and read the target, and return the number of bytes copied and the err information of the int64.
Import (
"fmt"
"io"
"os"
)
Func main () {
R, _: = os.Open ("test.txt")
W, _: = os.Create ("write.txt")
Num, err: = io.Copy (w, w)
If err! = nil {
Fmt.Println (err)
}
Fmt.Println (num) / / return 11 of int64 to open my write.txt is the hello widuu in test.txt
}
2.func CopyN (dst Writer, src Reader, n int64) (written int64, err error) look at the function and know that it is the same as above, except that there is an extra limit on the number of reads, and then let's take a look at the code.
The copy code is as follows:
Import (
"fmt"
"io"
"io/ioutil"
"os"
)
Func main () {
R, _: = os.Open ("test.txt")
W, _: = os.Create ("write1.txt")
Num, err: = io.CopyN (w, r, 5)
If err! = nil {
Fmt.Println (err)
}
Defer r.Close ()
B, _: = ioutil.ReadFile ("write1.txt")
Fmt.Println (string (b)) / / output hello
Fmt.Println (num) / / 5
}
3.func ReadAtLeast (r Reader, buf [] byte, min int) (n int, err error) this function reads data from the reader and puts it in our buf, limiting the minimum number of bytes to be read. If the data we read is less than the minimum reader, for example, if you set the value of min to 8, if the number of bytes you read is 5, you will return a `io.ErrShortBuffer`. If it is greater than that, it will return `io.ErrShortBuffer`. After reading, there will be `io.EOF`. Tell me more, ah, this Reader can be used as long as we meet this interface.
The copy code is as follows:
Type Reader interface {
Read (p [] byte) (n int, err error)
}
* File supports func (f * File) Read (b [] byte) (n int, err error)
The copy code is as follows:
Import (
"fmt"
"io"
"os"
)
Func main () {
R, _: = os.Open ("write1.txt")
B: = make ([] byte, 20)
Defer r.Close ()
Var total int
For {
N, err: = io.ReadAtLeast (r, b, 8)
If err = = nil {
Fmt.Println ("Read enough value:", string (b)) / / Read enough value: hello widuu
}
If err = = io.ErrUnexpectedEOF {/ / the read data is less than our limited minimum read data 8
Fmt.Println ("Read fewer value:", string (b [0: n]))
}
If err = = io.ErrShortBuffer {/ / this is the buf we set, that is, b is less than our limit of 8.
Fmt.Println ("buf too Short")
Os.Exit (1)
}
If err = = io.EOF {/ / finished reading the output
Fmt.Println ("Read end total", total) / / Read end total 11
Break
}
Total = total + n
}
}
4.func ReadFull (r Reader, buf [] byte) (n int, err error) is similar to the function above, except that it reads len (buf) and puts it in buf.
The copy code is as follows:
Import (
"fmt"
"io"
"os"
)
Func main () {
R, _: = os.Open ("write.txt")
B: = make ([] byte, 20)
Num, err: = io.ReadFull (r, b)
Defer r.Close ()
If err = = io.EOF {
Fmt.Println ("Read end total", num)
}
If err = = io.ErrUnexpectedEOF {
Fmt.Println ("Read fewer value:", string (b [: num])) / / Read fewer value: hello widuu, the buf length is still greater than the read length.
Return
}
Fmt.Println ("Read value:", string (b)) / / if b is 5, it appears here
}
5.func WriteString (w Writer, s string) (n int, err error) finished reading, of course, with writing, this function is mainly to write characters to the write target, the return is the number of bytes written and error errors, mainly permission errors, in which write ah! All writer can be written in this structure.
The copy code is as follows:
Type Writer interface {
Write (p [] byte) (n int, err error)
}
Like read, our * File has func (f * File) Write (b [] byte) (n int, err error). Of course, we already have WirteString in our * File. Func (f * File) WriteString (s string) (ret int, err error)
Import (
"fmt"
"io"
"io/ioutil"
"os"
)
Func main () {
W, _: = os.OpenFile ("write1.txt", os.O_RDWR, os.ModePerm)
N, err: = io.WriteString (w, "ni hao ma")
If err! = nil {
Fmt.Println (err) / / when I use os.open (), I don't have permission to output write write1.txt: Access is denied.
}
Defer w.Close ()
B, _: = ioutil.ReadFile ("write1.txt")
Fmt.Println ("write total", n) / / write total 9
Fmt.Println (string (b)) / / ni hao ma
}
6.type LimitedReader
The copy code is as follows:
Type LimitedReader struct {
R Reader / / Reader
N int64 / / maximum byte limit
}
There is only one method func (l * LimitedReader) Read (p [] byte) (n int, err error). In fact, it is not difficult for us to find that this and our ReadAtLast () is the rhythm of our brothers.
The copy code is as follows:
Import (
"fmt"
"io"
"os"
)
Func main () {
Reader, _: = os.Open ("test.txt")
Limitedreader: = io.LimitedReader {
R: reader
N: 20
}
P: = make ([] byte, 10)
Var total int
For {
N, err: = limitedreader.Read (p)
If err = = io.EOF {
Fmt.Println ("read total", total) / / read total 11
Fmt.Println ("read value", string (p)) / / read value hello widuu
Break
}
Total = total + n
}
}
7.type PipeReader
The copy code is as follows:
Type PipeReader struct {
/ / contains filtered or unexported fields
}
(1) func Pipe () (* PipeReader, * PipeWriter) creates a pipe and returns its reader and writer. This will synchronize the pipe in memory. Its opening will io.Reader and wait for the input of io.Writer. There is no internal buffer. It is safe to call Read and Write each other and write in parallel.
The copy code is as follows:
Import (
"fmt"
"io"
"reflect"
)
Func main () {
R, w: = io.Pipe ()
Fmt.Println (reflect.TypeOf (r)) / / * io.PipeReader
Fmt.Println (reflect.TypeOf (w)) / / * io.PipeWriter
}
(2) after the func (r * PipeReader) Close () error pipeline is closed, the write Write operation in progress or subsequent operation returns ErrClosedPipe
The copy code is as follows:
Import (
"fmt"
"io"
)
Func main () {
R, w: = io.Pipe ()
R.Close ()
_, err: = w.Write ([] byte ("hello widuu"))
If err = = io.ErrClosedPipe {
Fmt.Println ("the pipe has been closed and cannot be written") / / the pipe has been closed and cannot be written
}
}
(3) func (r * PipeReader) CloseWithError (err error) error this is when the above r.Close is closed, the writer will return an error message
The copy code is as follows:
Import (
"errors"
"fmt"
"io"
)
Func main () {
R, w: = io.Pipe ()
R.Close ()
Err: = errors.New ("pipe character is off") / / errors this package we have already talked about, there is only one method New will not, you can take a look at the previous one.
R.CloseWithError (err)
_, err = w.Write ([] byte ("test"))
If err! = nil {
The fmt.Println (err) / / pipe character is closed
}
}
(4) the standard reading interface of func (r * PipeReader) Read (data [] byte) (n int, err error), which reads data from the pipeline and blocks until a write interface is closed. If an error occurs on the write side, it will return an error, otherwise the returned EOF
The copy code is as follows:
Import (
"fmt"
"io"
)
Func main () {
R, w: = io.Pipe ()
Go w.Write ([] byte ("hello widuu"))
D: = make ([] byte, 11)
N, _: = r.Read (d) / / read data from the pipe
Fmt.Println (string (d))
Fmt.Println (n)
}
At this point, the study on "how to read and write files in Go language" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.