I. Basic API for file operation
func main() { //Absolute path fileInfo , err := os.Stat("E:/a.txt") fileInfo , err = os.Stat("E:/") if err !=nil { fmt.Println("err:" , err.Error()) } else { fmt.Printf("%T \n" , fileInfo) fmt.Printf("%v \n" , fileInfo) //file name fmt.Println(fileInfo.Name()) //Is it a directory fmt.Println(fileInfo.IsDir()) //File size size fmt.Println(fileInfo.Size()) //mode Jurisdiction fmt.Println(fileInfo.Mode()) //File last modified fmt.Println(fileInfo.ModTime()) } }
File path:
- 1. Absolute path: absolute
- 2. Relative path: relative is equivalent to the current project (. Current directory.. upper level)
(1) judge whether it is the absolute path filepath.IsAbs()
(2) get the relative path filepath.Rel()
(3) get the absolute path filepath.Abs()
(4) path.Join()
File operation:
1. Create the folder. If the folder exists, the creation fails
- os.MKdir()
- os.MKdirAll()
2. Create file: if the file exists, it will be overwritten
- os.Create()-->*file
3. Open file:
- os.Open(filename)
- os.OpenFile(filename,mode,perm)
4. Close file:
- file.Close()
5. delete:
- os.Remove()
- os.RemoveAll()
package main import ( "os" "fmt" ) func main() { /* File operation: 1.Create folder. If the folder exists, the creation fails os.MKdir() os.MKdirAll() 2.Create file: overwrite if file exists os.Create()-->*file 3.Open file: os.Open(filename) os.OpenFile(filename,mode,perm) 4.Close file: file.Close() 5.Delete: os.Remove() os.RemoveAll() */ // 1,Create directory fileName1 := "./test1" err := os.Mkdir(fileName1, os.ModePerm) if err != nil { fmt.Println("err:", err.Error()) } else { fmt.Printf("%s Directory created successfully!\n", fileName1) } fileName2 := "./test2/abc/xyz" err = os.MkdirAll(fileName2, os.ModePerm) if err != nil { fmt.Println("err:", err.Error()) } else { fmt.Printf("%s Directory created successfully!\n", fileName2) } //2,create a file.If the file already exists, the file is overwritten fileName3 := "./test1/abc.txt" file1, err := os.Create(fileName3) if err != nil { fmt.Println("err:", err.Error()) } else { fmt.Printf("%s Created successfully!%v \n", fileName3, file1) } // 3,Open file file2, err := os.Open(fileName3) if err != nil { fmt.Println("err:", err.Error()) } else { fmt.Printf("%s Open successfully!%v \n", fileName3, file2) } /* First parameter: file name Second parameter: how to open the file O_RDONLY: Read only mode O_WRONLY: Write only mode O_RDWR: Read write mode O_APPEND: Append mode O_CREATE: create a new file if none exists The third parameter: permission of file: the file does not exist. You need to specify permission */ fileName4 := "./test1/abc2.txt" file4, err := os.OpenFile(fileName4, os.O_RDWR|os.O_CREATE, os.ModePerm) if err != nil { fmt.Println("err:", err.Error()) } else { fmt.Printf("%s Open successfully!%v \n", fileName4, file4) } //4,Close the file and disconnect the program from the file file4.Close() // 5,Delete files and directories fileName5 := "./test1" err = os.Remove(fileName5) if err != nil { fmt.Println(err) } else { fmt.Printf("%s Delete successfully!" , fileName5) } err = os.RemoveAll(fileName5) if err != nil { fmt.Println(err) } else { fmt.Printf("%s Delete successfully!" , fileName5) } }
File read / write
/** 2.Read file. Read ([] byte) -- > N, err starts to read data from the file and stores it in the byte slice. The return value n is the actual amount of data read this time. If read to the end of the file, n is 0,err is EOF: end of file. */ func readFile(fileName string){ file2,err:=os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, os.ModePerm) if err!=nil{ fmt.Println(file2); }else { bs:=make([]byte,8,1024*8); n:= -1; str:=""; for{ n,err=file2.Read(bs); fmt.Printf("n:%v \n",n) if n==0||err==io.EOF{ fmt.Println("read file end") break; } str= strings.Join([]string{str,string(bs[:n])},"") } fmt.Println(str) } //3,Close file file2.Close() } func writeFile(fileName string){ str:="I Love China I love China"; bs:=[]byte(str); file2,err:=os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, os.ModePerm) if err!=nil{ fmt.Println(file2); }else { file2.Write(bs); } file2.Close(); }
II. ioutil package
/*
ioutil bag:
ReadFile() / / read all the data in the file and return the byte array read
WriteFile() / / writes data to the specified file. If the file does not exist, create the file and empty the file before writing the data
ReadDir() / / read the sub contents of a directory: sub files and sub directories, but only one layer
TempDir() / / in the current directory, create a temporary folder prefixed with the specified string and return the folder path
TempFile() / / in the current directory, create a file prefixed with the specified string, open the file in read-write mode, and return the os.File pointer object
*/
package main import ( "io/ioutil" "fmt" "os" ) func main() { /* ioutil Bag: ReadFile() //Read all the data in the file and return the byte array read WriteFile() //Write data to the specified file. If the file does not exist, create the file and empty the file before writing the data ReadDir() //Read the sub contents of a directory: sub files and sub directories, but only one layer TempDir() //In the current directory, create a temporary folder prefixed with the specified string and return the folder path TempFile() //In the current directory, create a file prefixed with the specified string, open the file in read-write mode, and return the os.File pointer object */ //1,ReadFile() //Read all the data in the file and return the byte array read fileName1 := "./files/blockchain.txt" data, err := ioutil.ReadFile(fileName1) if err != nil { fmt.Println("File open exception", err.Error()) } else { fmt.Println(string(data)) } //2,WriteFile() //Write data to the specified file. If the file does not exist, create the file and empty the file before writing the data fileName2 := "./files/xyz.txt" s1 := "Steven With your school district block chain" err = ioutil.WriteFile(fileName2, []byte(s1), 0777) if err != nil { fmt.Println("Write file exception", err.Error()) } else { fmt.Println("File write OK!") } //3,File copy err = ioutil.WriteFile(fileName2 , data , os.ModePerm) if err != nil { fmt.Println("File copy exception", err.Error()) } else { fmt.Println("File copied successfully!") } //4,ReadDir() //Read the sub contents of a directory: sub files and sub directories, but only one layer dirName := "./" fileInfos , err := ioutil.ReadDir(dirName) if err != nil { fmt.Println("Directory traversal exception", err.Error()) } else { for i , v := range fileInfos { fmt.Println(i , v.Name() , v.IsDir() , v.Size() , v.ModTime()) } } //5,TempDir() //In the current directory, create a temporary folder prefixed with the specified string and return the folder path filename , err := ioutil.TempDir("./" , "temp") if err != nil { fmt.Println("Failed to create directory" , err.Error()) } else { fmt.Println(filename) } //6,TempFile() //In the current directory, create a file prefixed with the specified string, open the file in read-write mode, and return os.File Pointer object file1 , err := ioutil.TempFile(filename , "temp") if err != nil { fmt.Println("Failed to create file" , err.Error()) } else { file1.WriteString("Write contents:" + file1.Name()) } file1.Close() }