In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
In this article Xiaobian for you to introduce in detail the "GO file creation and read and write operation methods", the content is detailed, the steps are clear, the details are handled properly, I hope this "GO file creation and reading and writing operation methods" article can help you solve your doubts, the following follow the editor's ideas slowly in-depth, together to learn new knowledge bar.
Comparison of the three file operations ioutilbufioos.File when the file is small (KB level), ioutil > bufio > os. When the file size is more regular (MB level), there is little difference between the three, but bufio has already emerged. When the file is large (GB level), bufio > os > ioutil. Ioutilioutil.ReadFile read / / read func Ioutil_read () {file, _: = ioutil.ReadFile (". / write.txt") fmt.Println (string (file))} ioutil.WriteFile write / / write func Ioutil_write () {ioutil.WriteFile (". / write.txt", [] byte ("aaaa\ nbbb\ ncccc\ nLara"), 0777)} ioutil.ReadAll read / / waste memory, solution Baidu query file,_: = os.Open (". / write.txt") b for to view the directory information under the path func Ioutil_ReadDir () {dir,_:=ioutil.ReadDir (". /") for _ File: = range dir {fmt.Println (file.Name ()) / / File name fmt.Println (file.Size ()) / / File size fmt.Println (file.IsDir ()) / / determine whether it is a directory fmt.Println (file.Mode ()) / / View read and write permissions-rw-r--r-- Fmt.Println (file.ModTime ()) / / File creation time}} ioutil.TempDir create temporary directory / / create temporary directory Start with jeff, eg:jeff0123755func Ioutil_Tempdir () {path,_: = ioutil.TempDir (". /", "jeff") fmt.Println (path) / / return temporary directory path} ioutil.TempFile create temporary file / / create temporary file, starting with jeff Eg:jeff067576func Ioutil_file () {/ / opens the file in read-write mode and returns the os.File pointer path,_:=ioutil.TempFile (". /", "jeff") fmt.Println (path) / / returns the os.File pointer} os.file method os.Create () / / creates a file, and if there is a file, it clears the file os.Open () / / opens the file os.OpenFile (file name only). Open mode, open permission) Write () / write Read () / / read os.OpenFile () OpenFile () this function has three parameters, the first parameter represents the path to open the file, the second parameter represents the mode, the common modes are O_RDONLY (read-only mode), O_WRONLY (write-only mode), O_RDWR (read-write mode), O_APPEND (append mode). The third parameter, indicates permission, and the value range (0-7) is as follows: 0: no permission 1: execute permission (if it is an executable file, it can be run) 2: write permission 3: write permission and execution permission 4: read permission 5: read permission and execution permission 6: read permission and write permission 7: read permission, write permission Execute permission fp,err: = os.OpenFile ("D:/a.txt", os.O_RDWR,6) if erratic file nil {fmt.Println ("file failed")} fp.WriteString ("hello") fp.WriteAt ([] byte ("hello"), 25) defer fp.Close () create file
Before saving data to a file, create a file. The GO language provides a Create () function specifically for creating files.
When creating a file, this function first determines whether the file to be created exists, if not, then creates it, and if so, empties the existing data in the file first.
At the same time, when the file is created successfully, the file will be opened by default, so you can write data directly to the file without performing the open operation.
To create a file:
(1) Import "os" package, create files, and read and write files are all in this package.
(2) specify the storage path and file name of the created file.
(3) execute the Create () function to create the file
(4) close the document
Specific code:
Package mainimport ("fmt"os") func main () {/ / os.Create (filename) filename can write absolute path and relative path / / return value file pointer error message fp,err: = os.Create (". / a.txt") if erratic error nil {/ / file creation failed / * 1. Path does not exist 2. File permissions 3. Program open file limit * / fmt.Println ("file creation failed") return} / / read and write file defer fp.Close () / close file / / if open file does not close memory waste program open file upper limit / / fp.Close ()} there are three ways to write data-WriteString ( ) function WriteString () method returns two parameters by default The first parameter refers to the length of data written to the file, and the second parameter records the error message that the data written to the file by default by the WriteString () method does not wrap. If you want to break lines, you can use the following methods: / /\ nNo line breaks in windows text file for reasons of line breaks\ r\ nenter enter line breaks in linux\ nfp.WriteString ("hello world\ r\ n") fp.WriteString ("Sexy Holdings online Licensing")
After the file is opened, you can write data to the file, using the WriteString () method.
You can use / forward slash instead of\ backslash fp,err: = os.Create ("D:/a.txt") if erratic escape nil {/ / file creation failed / * 1 when writing the path. Path does not exist 2. File permissions 3. The program opens the file limit * / fmt.Println ("file creation failed") return} / / write file / /\ nNo line wrapping reason in windows text file\ r\ nenter newline in linux\ nfp.WriteString ("hello world\ r\ n") fp.WriteString ("Sexy official online Licensing") defer fp.Close () / close the file / / if the file is opened Do not close the upper limit of files opened by programs that cause memory waste / / fp.Close () the second-Write () function should be noted here When you use the Write () function to write data, the argument is a byte slice, so you need to convert the string to a byte slice. This method also returns the length fp,err: = os.Create ("D:/a.txt") if erratically created nil {/ / file creation failed / * 1. Path does not exist 2. File permissions 3. The upper limit of the program opening file * / fmt.Println ("file creation failed") return} / / write operation / / slice: = [] byte {'haggling pamphlet, pyrrhenol, count,err1, count,err1: = fp.Write (file creation) count Err1: = fp.Write ([] byte ("Sexy Lao Wang teaches online")) if err1failed teachnil {fmt.Println ("failed to write to file") return} else {fmt.Println (count)} defer fp.Close () the third-WriteAt () function
The data is written at the specified location, and the return value of the Seek () function in the following program is stored in variable n, and the value is the location at the end of the file. WriteAt () also returns the length of the data written.
Fp,err: = os.Create ("D:/a.txt") if erratically created nil {/ / file creation failed / * 1. Path does not exist 2. File permissions 3. The program opens the upper limit of the file * / fmt.Println ("file creation failed") return} / / write operation / / get the cursor stream location'/ / get the number of characters / / count,_:=fp.Seek (0philosophy os.SEEKSeiEND) count,_:=fp.Seek (0memio.SeekEnd) fmt.Println (count) / / write to fp.WriteAt ([] byte ("hello world") at the specified location from the beginning to the end of the file. Count) fp.WriteAt ([] byte (""), 0) fp.WriteAt ([] byte ("Xiuer"), 19) defer fp.Close () read file Read read file
If the file already exists and already has data, you can read the contents of the file directly.
The basic process for reading a file is as follows:
(1) Open the file to be read
(2) read the file
(3) close the document
When writing data to a file, you use Write, so read the data in the file using Read.
The use of the Read () function is as follows:
Package mainimport ("fmt"io"os") func main () {/ / Open file fp, err: = os.Open ("D:/a.txt") if err! = nil {fmt.Println ("err=", err) return} buf: = make ([] byte, 1024x2) / / 2k size / / n represents the length of content read from the file n Err1: = fp.Read (buf) if err1! = nil & & err1! = io.EOF {fmt.Println ("err1=", err1) return} fmt.Println ("buf=", string (buf [: n])) / / close the file defer fp.Close ()}
Open () opens the file. Unlike OpenFile (), Open () only has read permissions.
When using the Read () function to read the contents of the file, you need a slice type, and define the slice type as a character array, save the contents of the file in the slice, and determine whether it is at the end of the file (here you need to import the io package) in addition to judging whether it is wrong.
The Read () function returns the length of the data read from the file. Finally, output the file data stored in the slice, note that it is read from the beginning to the entire data length, because the data stored in the slice may not reach the total length of the slice (also 2k when slicing, but the data read from the file may be only 1k).
Read by line
Above, we read out all the contents of the file and store it in a slice, or we can read only one row of data at a time.
This requires the ReadBytes function in the bufio package. The details are as follows:
1: open the file
Fp, err: = os.Open ("D:/a.txt") if err! = nil {fmt.Println ("failed to open file", err) return}
2: create a buffer
When using the ReadBytes () function to read data, we need to use a buffer. The so-called buffer is the area where the data is stored, that is, the data read from the file is first stored in this area, and then the data in the area is taken out and written to disk. The reason for providing a buffer is:
In order to ease the speed mismatch between CPU and disk devices. A file buffer is a certain amount of space reserved in the memory area for temporarily storing file data during reading and writing.
/ / create file buffer r: = bufio.NewReader (fp)
3: cycle through the contents of the file to the end of the file.
For {/ / encountered'\ n' to finish reading, but'\ n' also read into buf,err: = r.ReadBytes ('\ n') fmt.Println ("buf =", string (buf)) if err! = nil {if err= = io.EOF {break} fmt.Println ("err=", err)}}
When using the ReadBytes () function, the argument passed is'\ n', which means it ends when it encounters'\ n', so an endless loop (reading a row of data per loop) is used, and the entire loop is not exited until the end of the file. Finally, print out the read data, and notice that ReadBytes () returns a byte slice, so convert it to a string when printing.
4: finally close the file
/ / close the file defer fp.Close ()
Now that we have finished creating, reading, and saving data to the file, we need to specify the path to the file.
With regard to paths, there are two situations:
First: the relative path, which refers to the path of the file relative to the application. For example: above we only use the a.txt, this file, the location of the file is the same as the path of the executable file storage.
Second: absolute path: it means that this file can be found directly on my computer through the given path. For example: d:\ Info.txt
It is recommended that we use relative paths in development in the future.
File operation case
Copy the file, make a copy of the existing file and rename it at the same time.
Basic ideas:
(1) ask the user to enter the name of the file to be copied (the source file) and the name of the destination file
(2) create the destination file
(3) Open the source file and read the contents of the file
(4) write what is read from the source file to the destination file.
Var srcFileName stringvar dstFileName stringfmt.Printf ("Please enter source file name:") fmt.Scan (& srcFileName) fmt.Println ("Please enter destination file name:") fmt.Scan (& dstFileName) if srcFileName = = dstFileName {fmt.Println ("source and destination file names cannot be the same") return} / / Open source file sF,err1: = os.Open (srcFileName) if err1! = nil {fmt.Println ("err1=") Err1) return} / / New destination file dF,err2: = os.Create (dstFileName) if err2! = nil {fmt.Println ("err2=", err2) return} / / completed You need to close the file defer sF.Close () defer dF.Close () / / core processing, read from the source file, and write to the destination file. Buf: = make ([] byte,4*1024) / / 4k size temporary buffer for {njournal err: = sF.Read (buf) / / read from the source file, if err! = nil {fmt.Println ("err=", err) if err= = io.EOF {/ / file read finished break}} / / write to the destination file Read how much to write how many dF.Write (buf [: n])} read here, this "GO document creation and reading and writing methods" article has been introduced, want to master the knowledge of this article also need to practice and use in order to understand, if you want to know more related articles, welcome to follow the industry information channel.
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.