go库函数之-path-使用示例

//########################################################
//D:\go\go\go库源码\源码库测试文件集合\path-example_test.go

// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package path_test

import (
   "fmt"
   "path"
)

func ExampleBase() {
   // 返回路径的最后一个元素,在提取元素前会删掉末尾的斜杠
   // 如果路径是"",会返回".";如果路径是只有一个斜杆构成,会返回"/"
   //path.Base(pathStr)
   fmt.Println(path.Base("/a/b"))
   fmt.Println(path.Base("/"))
   fmt.Println(path.Base(""))
   // Output:
   // b
   // /
   // .
}

func ExampleClean() {
   paths := []string{
      "a/c",
      "a//c",
      "a/c/.",
      "a/c/b/..",
      "/../a/c",
      "/../a/b/../././/c",
      "",
   }

   for _, p := range paths {
      // 通过单纯的词法操作返回和path代表同一地址的最短路径
      // 它会不断的依次应用如下的规则,直到不能再进行任何处理:
      // 1. 将连续的多个斜杠替换为单个斜杠
      // 2. 剔除每一个.路径名元素(代表当前目录)
      // 3. 剔除每一个路径内的..路径名元素(代表父目录)和它前面的非..路径名元素
      // 4. 剔除开始一个根路径的..路径名元素,即将路径开始处的"/.."替换为"/"
      //path.Clean("a//c") // a/c
      fmt.Printf("Clean(%q) = %q\n", p, path.Clean(p))
   }

   // Output:
   // Clean("a/c") = "a/c"
   // Clean("a//c") = "a/c"
   // Clean("a/c/.") = "a/c"
   // Clean("a/c/b/..") = "a/c"
   // Clean("/../a/c") = "/a/c"
   // Clean("/../a/b/../././/c") = "/a/c"
   // Clean("") = "."
}

func ExampleDir() {
   // 返回路径除去最后一个路径元素的部分,即该路径最后一个元素所在的目录
   // 在使用Split去掉最后一个元素后,会简化路径并去掉末尾的斜杠
   // 如果路径是空字符串,会返回".";如果路径由1到多个斜杠后跟0到多个非斜杠字符组成,会返回"/";其他任何情况下都不会返回以斜杠结尾的路径
   //path.Dir(pathStr)
   fmt.Println(path.Dir("/a/b/c"))
   fmt.Println(path.Dir("a/b/c"))\
   fmt.Println(path.Dir("/a/"))
   fmt.Println(path.Dir("a/"))
   fmt.Println(path.Dir("/"))
   fmt.Println(path.Dir(""))
   // Output:
   // /a/b
   // a/b
   // /a
   // a
   // /
   // .
}

func ExampleExt() {
   // 返回path文件扩展名
   fmt.Println(path.Ext("/a/b/c/bar.css"))
   fmt.Println(path.Ext("/"))
   fmt.Println(path.Ext(""))
   // Output:
   // .css
   //
   //
}

func ExampleIsAbs() {
   // 返回路径是否是一个绝对路径
   fmt.Println(path.IsAbs("/dev/null"))
   // Output: true
}

func ExampleJoin() {
   // 可以将任意数量的路径元素放入一个单一路径里,会根据需要添加斜杠
   // 结果是经过简化的,所有的空字符串元素会被忽略
   fmt.Println(path.Join("a", "b", "c"))
   fmt.Println(path.Join("a", "b/c"))
   fmt.Println(path.Join("a/b", "c"))
   fmt.Println(path.Join("", ""))
   fmt.Println(path.Join("a", ""))
   fmt.Println(path.Join("", "a"))
   // Output:
   // a/b/c
   // a/b/c
   // a/b/c
   //
   // a
   // a
}

func ExampleMatch() {
   // 如果name匹配shell文件名模式匹配字符串,Match函数返回真
   // Match要求匹配整个name字符串,而不是它的一部分。只有pattern语法错误时,会返回ErrBadPattern
   /*
      匹配字符串语法:
         pattern:
            { term }
         term:
            '*'                                  匹配0或多个非/的字符
            '?'                                  匹配1个非/的字符
            '[' [ '^' ] { character-range } ']'  字符组(必须非空)
            c                                    匹配字符c(c != '*', '?', '\\', '[')
            '\\' c                               匹配字符c
         character-range:
            c           匹配字符c(c != '\\', '-', ']')
            '\\' c      匹配字符c
            lo '-' hi   匹配区间[lo, hi]内的字符
   */
   fmt.Println(path.Match("abc", "abc"))
   fmt.Println(path.Match("a*", "abc"))
   fmt.Println(path.Match("a*/b", "a/c/b"))
   // Output:
   // true <nil>
   // true <nil>
   // false <nil>
}

func ExampleSplit() {
   // 将路径从最后一个斜杠后面位置分隔为两个部分(dir和file)并返回
   // 如果路径中没有斜杠,函数返回值dir会设为空字符串,file会设为path
   // 两个返回值满足path == dir+file
   fmt.Println(path.Split("static/myfile.css"))
   fmt.Println(path.Split("myfile.css"))
   fmt.Println(path.Split(""))
   // Output:
   // static/ myfile.css
   //  myfile.css
   //
}

#################################################################
D:\go\go\go库源码\源码库测试文件集合\path-filepath-example_test.go

// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package filepath_test

import (
   "fmt"
   "path/filepath"
)

func ExampleExt() {
   // 返回path文件扩展名
   fmt.Printf("No dots: %q\n", filepath.Ext("index"))
   fmt.Printf("One dot: %q\n", filepath.Ext("index.js"))
   fmt.Printf("Two dots: %q\n", filepath.Ext("main.test.js"))
   // Output:
   // No dots: ""
   // One dot: ".js"
   // Two dots: ".js"
}

######################################################################
D:\go\go\go库源码\源码库测试文件集合\path-filepath-example_unix_test.go

// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build !windows,!plan9

package filepath_test

import (
   "fmt"
   "path/filepath"
)

func ExampleSplitList() {
   //将路径使用路径列表分隔符分开,见os.PathListSeparator
   //linux下默认为:,windows下为;
   //fmt.Println(filepath.SplitList("C:/windows;C:/windows/system"))
   fmt.Println("On Unix:", filepath.SplitList("/a/b/c:/usr/bin"))
   // Output:
   // On Unix: [/a/b/c /usr/bin]
}

func ExampleRel() {
   paths := []string{
      "/a/b/c",
      "/b/c",
      "./b/c",
   }
   base := "/a"

   fmt.Println("On Unix:")
   for _, p := range paths {
      //返回以basepath为基准的相对路径
      //path3, _ := filepath.Rel("C:/a/b", "C:/a/b/c/d/../e")
      //fmt.Println(path3)
      // 以/a为基准的相对路径
      rel, err := filepath.Rel(base, p)
      fmt.Printf("%q: %q %v\n", p, rel, err)
   }

   // Output:
   // On Unix:
   // "/a/b/c": "b/c" <nil>
   // "/b/c": "../b/c" <nil>
   // "./b/c": "" Rel: can't make ./b/c relative to /a
}

func ExampleSplit() {
   paths := []string{
      "/home/arnie/amelia.jpg",
      "/mnt/photos/",
      "rabbit.jpg",
      "/usr/local//go",
   }
   fmt.Println("On Unix:")
   for _, p := range paths {
      //分割路径中的目录与文件
      //dir, file := filepath.Split("C:/a/b/c/d.jpg");
      //fmt.Println(dir, file);
      dir, file := filepath.Split(p)
      fmt.Printf("input: %q\n\tdir: %q\n\tfile: %q\n", p, dir, file)
   }
   // Output:
   // On Unix:
   // input: "/home/arnie/amelia.jpg"
   //     dir: "/home/arnie/"
   //     file: "amelia.jpg"
   // input: "/mnt/photos/"
   //     dir: "/mnt/photos/"
   //     file: ""
   // input: "rabbit.jpg"
   //     dir: ""
   //     file: "rabbit.jpg"
   // input: "/usr/local//go"
   //     dir: "/usr/local//"
   //     file: "go"
}

func ExampleJoin() {
   fmt.Println("On Unix:")
   // 将新的文件夹路径放入一个单一路径里
   fmt.Println(filepath.Join("a", "b", "c"))
   fmt.Println(filepath.Join("a", "b/c"))
   fmt.Println(filepath.Join("a/b", "c"))
   fmt.Println(filepath.Join("a/b", "/c"))
   // Output:
   // On Unix:
   // a/b/c
   // a/b/c
   // a/b/c
   // a/b/c
}

func ExampleMatch() {
   fmt.Println("On Unix:")
   //匹配文件名,完全匹配则返回true
   fmt.Println(filepath.Match("/home/catch/*", "/home/catch/foo"))
   fmt.Println(filepath.Match("/home/catch/*", "/home/catch/foo/bar"))
   fmt.Println(filepath.Match("/home/?opher", "/home/gopher"))
   fmt.Println(filepath.Match("/home/\\*", "/home/*"))

   // Output:
   // On Unix:
   // true <nil>
   // false <nil>
   // true <nil>
   // true <nil>
}

func ExampleBase() {
   fmt.Println("On Unix:")
   //返回路径最后一个元素
   //如果路径为空字符串,返回.
   //如果路径只有斜线,返回/
   fmt.Println(filepath.Base("/foo/bar/baz.js"))
   fmt.Println(filepath.Base("/foo/bar/baz"))
   fmt.Println(filepath.Base("/foo/bar/baz/"))
   fmt.Println(filepath.Base("dev.txt"))
   fmt.Println(filepath.Base("../todo.txt"))
   fmt.Println(filepath.Base(".."))
   fmt.Println(filepath.Base("."))
   fmt.Println(filepath.Base("/"))
   fmt.Println(filepath.Base(""))

   // Output:
   // On Unix:
   // baz.js
   // baz
   // baz
   // dev.txt
   // todo.txt
   // ..
   // .
   // /
   // .
}

func ExampleDir() {
   fmt.Println("On Unix:")
   //返回路径最后一个元素的目录
   //路径为空则返回.
   fmt.Println(filepath.Dir("/foo/bar/baz.js"))
   fmt.Println(filepath.Dir("/foo/bar/baz"))
   fmt.Println(filepath.Dir("/foo/bar/baz/"))
   fmt.Println(filepath.Dir("/dirty//path///"))
   fmt.Println(filepath.Dir("dev.txt"))
   fmt.Println(filepath.Dir("../todo.txt"))
   fmt.Println(filepath.Dir(".."))
   fmt.Println(filepath.Dir("."))
   fmt.Println(filepath.Dir("/"))
   fmt.Println(filepath.Dir(""))

   // Output:
   // On Unix:
   // /foo/bar
   // /foo/bar
   // /foo/bar/baz
   // /dirty/path
   // .
   // ..
   // .
   // .
   // /
   // .
}

func ExampleIsAbs() {
   fmt.Println("On Unix:")
   //判断路径是不是绝对路径
   fmt.Println(filepath.IsAbs("/home/gopher"))
   fmt.Println(filepath.IsAbs(".bashrc"))
   fmt.Println(filepath.IsAbs(".."))
   fmt.Println(filepath.IsAbs("."))
   fmt.Println(filepath.IsAbs("/"))
   fmt.Println(filepath.IsAbs(""))

   // Output:
   // On Unix:
   // true
   // false
   // false
   // false
   // true
   // false
}

############################################################################
D:\go\go\go库源码\源码库测试文件集合\path-filepath-example_unix_walk_test.go

// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build !windows,!plan9

package filepath_test

import (
   "fmt"
   "io/ioutil"
   "os"
   "path/filepath"
)

func prepareTestDirTree(tree string) (string, error) {
   tmpDir, err := ioutil.TempDir("", "")
   if err != nil {
      return "", fmt.Errorf("error creating temp directory: %v\n", err)
   }

   err = os.MkdirAll(filepath.Join(tmpDir, tree), 0755)
   if err != nil {
      os.RemoveAll(tmpDir)
      return "", err
   }

   return tmpDir, nil
}

func ExampleWalk() {
   tmpDir, err := prepareTestDirTree("dir/to/walk/skip")
   if err != nil {
      fmt.Printf("unable to create test dir tree: %v\n", err)
      return
   }
   defer os.RemoveAll(tmpDir)
   os.Chdir(tmpDir)

   subDirToSkip := "skip"

   fmt.Println("On Unix:")
   err = filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
      if err != nil {
         fmt.Printf("prevent panic by handling failure accessing a path %q: %v\n", path, err)
         return err
      }
      if info.IsDir() && info.Name() == subDirToSkip {
         fmt.Printf("skipping a dir without errors: %+v \n", info.Name())
         return filepath.SkipDir
      }
      fmt.Printf("visited file or dir: %q\n", path)
      return nil
   })
   if err != nil {
      fmt.Printf("error walking the path %q: %v\n", tmpDir, err)
      return
   }
   // Output:
   // On Unix:
   // visited file or dir: "."
   // visited file or dir: "dir"
   // visited file or dir: "dir/to"
   // visited file or dir: "dir/to/walk"
   // skipping a dir without errors: skip
}

猜你喜欢

转载自blog.csdn.net/liao__ran/article/details/114673915