一、讀文件操作
func FileRead(path string) { file, err := os.Open(path) if err != nil { fmt.Println("open file err=", err) } rb := make([]byte, 1024, 1024) for { n, err := file.Read(rb) if n == 0 || err == io.EOF { fmt.Println("jieshu") break } fmt.Println(string(rb[:n])) } err = file.Close() if err != nil { fmt.Println(err) } } func Bufio(path string) { file, err := os.Open(path) if err != nil { fmt.Println("open file err=", err) } defer file.Close() /* const ( defaultBufSize = 4096 //默認的緩沖區為4096 ) */ // 創建一個 *Reader ,是帶緩沖區的 reader := bufio.NewReader(file) // 循環讀取文件的內容 for { str, err := reader.ReadString('\n') //讀到一個換行就結束 if err == io.EOF { // io.EOF 表示文件的末尾 break } // 輸出內容,如果是用Println會多出現一個空行,Println自帶換行 fmt.Printf(str) } fmt.Println("文件讀取結束!") } func IoUtil(path string) { // 使用ioutil.ReadFile 一次性將文件讀取(不適合大文件操作) filestr, err := ioutil.ReadFile(path) // filestr類型[]byte if err != nil { fmt.Println("open file err=", err) } // 把文件內容讀取到終端 fmt.Println(string(filestr)) // 沒有打開和關閉文件句柄,因為兩個操作都封裝到ReadFile函數內部 }
二、寫文件操作
func WriteHello(path string) { // 打開一個文件 /* const ( O_RDONLY int = syscall.O_RDONLY // 只讀模式打開文件 O_WRONLY int = syscall.O_WRONLY // 只寫模式打開文件 O_RDWR int = syscall.O_RDWR // 讀寫模式打開文件 O_APPEND int = syscall.O_APPEND // 寫操作時將數據附加到文件尾部 O_CREATE int = syscall.O_CREAT // 如果不存在將創建一個新文件 O_EXCL int = syscall.O_EXCL // 和O_CREATE配合使用,文件必須不存在 O_SYNC int = syscall.O_SYNC // 打開文件用於同步I/O O_TRUNC int = syscall.O_TRUNC // 如果可能,打開時清空文件 ) */ // 打開或者創建一個文件 file, err := os.OpenFile(path, os.O_CREATE|os.O_CREATE, 0644) if err != nil { fmt.Println("open file err=", err) } defer file.Close() str := "hello,Sonfer!\r\n" // 寫入時 使用帶緩存的 *Writer writer := bufio.NewWriter(file) for i := 0; i < 5; i++ { writer.WriteString(str) } // 因為writer是帶緩存,因此調用WriterString方法時, // 內容先寫到緩存的,所以調用Flush方法,將緩沖數據 // 真實寫入到文件中,否則文件中沒有數據! writer.Flush() } func WriteAppend(path string) { // 打開文件時追加內容,如果是os.O_TRUNC則清空文件內容在寫入 file, err := os.OpenFile(path, os.O_RDWR|os.O_APPEND, 0644) if err != nil { fmt.Println("open file err=", err) } defer file.Close() str := "追加的!\r\n" writer := bufio.NewWriter(file) for i := 0; i < 7; i++ { writer.WriteString(str) } writer.Flush() }
三、將一個文件內容寫入到另一個文件中
package main import ( "bufio" "fmt" "io" "os" ) func ReadWrite(srcpaht, despath string) { rdfile, err := os.Open(srcpaht) if err != nil { fmt.Println("open rdfile err=", err) } rwfile, err := os.OpenFile(despath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { fmt.Println("open rwfile err=", err) } defer rdfile.Close() defer rwfile.Close() // 創建讀寫緩沖區 reader := bufio.NewReader(rdfile) writer := bufio.NewWriter(rwfile) for { // 緩沖區中讀取行數 str, err := reader.ReadString('\n') if err == io.EOF { break } // 緩沖區中寫文件 writer.WriteString(str) } fmt.Println("over!") } func main() { sorfile := "G:\\GO\\1.txt" desfile := "G:\\GO\\2.txt" ReadWrite(sorfile, desfile) }
四、判斷一個文件是否存在
- 如果返回的錯誤為nil,說明文件或文件夾存在
- 如果返回的錯誤類型使用os.IsNotExist()判斷為true,說明文件或文件夾不存在
- 如果返回的錯誤為其它類型,則不確定是否在存在
func PathExists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return false, err }
五、拷貝文件
package main import ( "bufio" "errors" "fmt" "io" "os" ) func FileExit(path string) (bool, error) { _, err := os.Stat(path) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return false, err } // 編寫一個拷貝函數,接收兩個文件路徑,源文件存在,目標文件不存在 func CopyFile(destFile, srcFile string) (written int64, err error) { // 判斷源文件是否存在,0為隨意數字 srcfiletrue, err := FileExit(srcFile) if srcfiletrue == false { return 0, errors.New("源文件不存在!") } // 判斷目標文件是否存在,0為隨意數字 destfiletrue, err := FileExit(destFile) if destfiletrue == true { return 0, errors.New("目標文件已存在!") } // 通過srcFile獲取 Reader readfile, err := os.Open(srcFile) if err != nil { fmt.Println(err) } defer readfile.Close() reader := bufio.NewReader(readfile) //通過 destFile, 獲取到 Writer writefile, err := os.OpenFile(destFile, os.O_RDONLY|os.O_CREATE, 0644) if err != nil { fmt.Println(err) return } defer writefile.Close() writer := bufio.NewWriter(writefile) return io.Copy(writer, reader) } func main() { srcFile := "G:\\GO\\1.txt" destFile := "G:\\GO\\1.copy.txt" _, err := CopyFile(destFile, srcFile) if err == nil { fmt.Println("拷貝完成!") } else { fmt.Println("拷貝失敗,err:", err) } }
統計字符數量
package main import ( "bufio" "fmt" "io" "os" ) type CharCount struct { ChCount int NumCount int SpaceCount int OtherCount int } func main() { var count CharCount rdfile, err := os.Open("G:\\GO\\1.txt") if err != nil { fmt.Println("打開文件錯誤,err=", err) return } defer rdfile.Close() reader := bufio.NewReader(rdfile) for { str, err := reader.ReadString('\n') if err == io.EOF { break } fmt.Printf(str) for _, v := range []rune(str) { switch { case v >= 'a' && v <= 'z': fallthrough case v >= 'A' && v <= 'Z': count.ChCount++ case v == '\t' || v == ' ': count.SpaceCount++ case v >= '0' && v <= '9': count.NumCount++ default: count.OtherCount++ } } } fmt.Printf("字符的個數為:%v,數字的個數為:%v,空格的個數為:%v,其他字符為:%v", count.ChCount, count.NumCount, count.SpaceCount, count.OtherCount) }