filepath的使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| func main() { path, _ := filepath.Abs("./filepath.go") fmt.Println(path)
fmt.Println(filepath.Base("./filepath.go")) fmt.Println(filepath.Base("")) fmt.Println(filepath.Base("///"))
fmt.Println(filepath.Dir("/a/b/c.txt"))
fmt.Println(filepath.Clean("C:/a/b/../c")) fmt.Println(filepath.Clean("./1.txt"))
fmt.Println(filepath.Ext("/a/b/c.go"))
fmt.Println(filepath.IsAbs("/a/b/c")) fmt.Println(filepath.IsAbs("./a/b/c"))
dir, _ := filepath.Abs("/opt/cmdb") fmt.Println(filepath.Join(dir, "config", "conf.ini"))
Dir, base := filepath.Split("/etc/nginx/nginx.conf") fmt.Println(Dir, base)
paths := "/etc/nginx.conf:/etc/my.cnf:/etc/zookeeper.conf" fmt.Println(filepath.SplitList(paths))
fmt.Println(filepath.Glob("./*.go"))
fmt.Println(filepath.Match("*", "a")) fmt.Println(filepath.Match("*", "C:/a/b/c")) fmt.Println(filepath.Match("\\b", "b")) }
|
strings.Builder|Reader使用
不论是Builder
还是Reader
都是在内存中操作字符串的
Builder示例
与许多支持string
类型的语言一样,golang
中的string
类型也是只读且不可变的。因此,这种拼接字符串的方式会导致大量的string
创建、销毁和内存分配问题。可以使用strings.Builder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| func main() { var s strings.Builder
s.WriteString("我爱Go语言\n") s.Write([]byte("运维开发")) s.WriteRune('b') s.WriteByte('c')
fmt.Println(s.String())
fmt.Println(s.Len()) s.Reset() fmt.Println(s.Len()) }
|
Reader示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| func main() { reader := strings.NewReader("abcdefghijklmn123456789")
ctx := make([]byte, 10) for { n, err := reader.Read(ctx) if err != nil { break } fmt.Println(n, err, string((ctx[:n]))) }
reader.Seek(0, io.SeekStart) n, err := reader.Read(ctx) fmt.Println(n, err, string((ctx[:n])))
fmt.Println(reader.Size())
reader.Reset("123123123") n, err = reader.Read(ctx) fmt.Println(n, err, string((ctx[:n])))
reader.WriteTo(os.Stdout) }
|
bytes Buffer使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| func main() { buffer1 := bytes.NewBuffer([]byte("abc,"))
buffer2 := bytes.NewBufferString("123,")
buffer1.Write([]byte("xyz,")) buffer2.Write([]byte("789,"))
buffer1.WriteString("mn") buffer2.WriteString("55")
ctx := make([]byte,3) n,_ := buffer1.Read(ctx) fmt.Println(string(ctx[:n]))
n,_ = buffer2.Read(ctx) fmt.Println(string(ctx[:n]))
ctx,_ = buffer2.ReadBytes(',') fmt.Println(string(ctx))
ctx,_ = buffer1.ReadBytes(',') fmt.Println(string(ctx))
txt,_ := buffer1.ReadString(',') fmt.Println(string(txt))
txt,_ = buffer2.ReadString(',') fmt.Println(string(txt))
fmt.Println(string(buffer1.Bytes()))
fmt.Println(buffer1.String())
buffer1.WriteTo(os.Stdout)
buffer2.Reset() buffer2.WriteTo(os.Stdout) }
|