当前位置:网站首页>Go file operation

Go file operation

2022-04-23 17:52:00 Liu Yuanshan

Catalog

 Insert picture description here

File read and write

File read operation

1) Open and close files
Easy way to open a file , File operations , Close in one second

package main

import (
	"fmt"
	"os"
	"time"
)

func main() {
    
	file, err := os.Open("D:/go_work/src/demo/1.json")
	if err == nil {
    
		fmt.Println(" File opened successfully ")
	} else {
    
		fmt.Println(" File opening failure ,err=", err)
		return
	}
	defer func() {
    
		file.Close()
		fmt.Println(" The file is closed ")
	}()

	fmt.Println(" File operations ", file)
	time.Sleep(1 * time.Second)
}

2) Buffered file read in

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

func main() {
    
	// Open the file in read-only mode (0666 It means that everyone has read and write permission )
	file, err := os.OpenFile("D:/go_work/src/demo/1.json", os.O_RDONLY, 0666)

	// Judge whether the file is opened successfully 
	if err == nil {
    
		fmt.Println(" File opened successfully ")
	} else {
    
		fmt.Println(" File opening failure ,err=", err)
		return
	}

	// Time delay ( Before the function returns ) Close file - Before the function returns, it will execute defer Guided statement 
	defer func() {
    
		file.Close()
		fmt.Println(" The file is closed ")
	}()

	// Create a buffer reader for this file 
	reader := bufio.NewReader(file)

	// Loop in data 
	for {
    
		// Read in one line at a time 
		str, err := reader.ReadString('\n')

		// Judge whether the reading is successful 
		if err == nil {
    
			// Print the read string 
			fmt.Println(str)
		} else {
    
			if err == io.EOF {
    
				// End of file , Jump out of the read loop 
				fmt.Println(" End of file !")
				break
			} else {
    
				// There are other exceptions , Print the exception and end the program 
				fmt.Println(" Read failed ,err=", err)
				return
			}
		}
	}
	fmt.Println(" File read complete !")
}

3) Easy to read files

package main

import (
	"fmt"
	"os"
)

func main() {
    
	bytes, err := os.ReadFile("D:/go_work/src/demo/1.json")
	if err == nil {
    
		contentStr := string(bytes)
		fmt.Println(contentStr)
	} else {
    
		fmt.Println(" Read failed ,err=", err)
	}
}

File write operation

1) Buffered write

package main

import (
	"bufio"
	"fmt"
	"os"
)

/* With 【 gen - Write - Additional 】 or 【 gen - Write - Cover 】 Open a file in this way , Write out a few lines of data in buffer , Drain the buffer and exit ;*/
func main() {
    
	// Open the specified file , Pattern : Create... If it doesn't exist + Just write + Additional , The permissions of the generated file are -rw-rw-rw-
	file, err := os.OpenFile("D:/go_work/src/demo/1.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	// If there is any abnormality, print directly and exit 
	if err != nil {
    
		fmt.Println(" File opening failure ,err=", err)
		return
	}

	// Delay closing file 
	defer func() {
    
		file.Close()
		fmt.Println(" The file is closed ")
	}()

	// Write out the file buffer created by 
	writer := bufio.NewWriter(file)

	// Write some data in batches 
	writer.WriteString(" test \n")

	// Drain the buffer ( Write out the last bucket of data to the file immediately )
	writer.Flush()
	fmt.Println(" Write it out !")
}

2) Convenient write

package main

import (
	"fmt"
	"os"
)

func main() {
    
	data := " test "
	dataBytes := []byte(data)
	err := os.WriteFile("D:/go_work/src/demo/1.json", dataBytes,0666)

	if err !=nil{
    
		fmt.Println(err)
		return
	}
	fmt.Println("ok")
}

A copy of a document

1) Judge whether the file exists

package main

import (
	"fmt"
	"os"
)

func main() {
    
	fileInfo, err := os.Stat("D:/1go_work/src/demo/1.json")
	if err != nil {
    
		fmt.Println(err)
		if os.IsNotExist(err) {
    
			fmt.Println(" file does not exist ")
		}

	} else {
    
		fmt.Println(" File exists ", fileInfo)
	}

}

2) Easy copy of files

package main

import (
	"fmt"
	"os"
)

func main() {
    

	bytes, err := os.ReadFile("D:/go_work/src/demo/1.json")
	if err != nil {
    
		fmt.Println(err)
		if os.IsNotExist(err) {
    
			fmt.Println(" file does not exist ")
		}
	} else {
    
		err := os.WriteFile("D:/go_work/src/demo/2.json", bytes, 0666)
		if err != nil {
    
			fmt.Println(err)
		}
		fmt.Println(" Success copy ")
	}

}

3)io.Copy(dstFile,srcFile) Use

package main

import (
	"fmt"
	"io"
	"os"
)

func main() {
    
	// Open the copy source file , Note that the mode is read-only 
	srcFile, _ := os.OpenFile("D:/go_work/src/demo/1.json", os.O_RDONLY, 0666)
	// Open the target file you want to copy to , Pay attention to the mode : establish + Write 
	dstFile, _ := os.OpenFile("D:/go_work/src/demo/2.json", os.O_WRONLY|os.O_CREATE, 0666)
	// Execute the copy from source file to target file 
	written, err := io.Copy(dstFile, srcFile)
	// Judge the execution result 
	if err == nil {
    
		fmt.Println(" Success copy , Number of bytes =", written)
	} else {
    
		fmt.Println(" Copy failure ", err)
	}
}

4) Buffered copy
Suitable for big documents , It doesn't need to be stored in the cache at one time, which takes up a lot of cache , Adopt one pass and one bucket split buffer storage

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

/* Use buffer 1K The buffer of is used to copy pictures with the buffer reader */
func main() {
    
	// open the source file 
	srcFile, _ := os.OpenFile("D:/go_work/src/demo/1.mp4", os.O_RDONLY, 0666)
	// Open the target file 
	dstFile, _ := os.OpenFile("D:/go_work/src/demo/2.mp4", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	// Delay closing them 
	defer func() {
    
		srcFile.Close()
		dstFile.Close()
		fmt.Println(" All files are closed !")
	}()

	// Create a buffer reader for the source file 
	reader := bufio.NewReader(srcFile)
	// The writer that creates the target file 
	writer := bufio.NewWriter(dstFile)

	// Create a small bucket ( buffer )
	buffer := make([]byte, 1024)

	// Read data bucket by bucket into the bucket ( buffer ), until io.EOF
	for {
    
		_, err := reader.Read(buffer)
		if err != nil {
    
			if err == io.EOF {
    
				fmt.Println(" Finished reading source file !")
				break
			} else {
    
				fmt.Println(" Error reading source file ,err=", err)
				return
			}
		} else {
    
			// Write out a barrel of data to the target file 
			_, err := writer.Write(buffer)
			if err != nil {
    
				fmt.Println(" Write mistakes ,err=", err)
				return
			}
		}
	}

	fmt.Println(" Copy complete !")
}

版权声明
本文为[Liu Yuanshan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231751425092.html