欢迎加入QQ讨论群258996829

Swift 文件管理框架 FileKit

发布时间:2017-02-21 22:28  回复:0  查看:6751  感兴趣:67  赞:1   最后回复:2017-02-21 22:28  

FileKit是一个简单且可以使用表达式来管理文件的Swift框架。

示例代码:

路径

通过Path结构体创建路径。

1let home = Path("~")
2let drive: Path = "/Volumes/Macintosh HD"
3let file:  Path = "~/Desktop/file\(1)"
新建文件

可以通过在Path上调用createFile()来编写空白文件。

1try Path(".gitignore").createFile()
新建目录

可以通过在Path上调用createDirectory()来创建目录。

1try Path("~/Files").createDirectory()
2try Path("~/Books").createDirectory(withIntermediateDirectories: false)
创建符号链接

可以通过在Path上调用createSymlinkToPath(_:)创建符号链接。

1try Path("path/to/MyApp.app").symlinkFile(to: "~/Applications")
2print(Path("~/Applications/MyApp.app").exists)  // true
查找路径

在桌面的5个层级目录内查找所有.txt后缀的文件。

1let textFiles = Path.userDesktop.find(searchDepth: 5) { path in
2    path.pathExtension == "txt"
3}

使用searchDepth来指定查找的目录层级。

迭代路径

1for download in Path.userDownloads {
2    print("Downloaded file: \(download)")
3}

当前工作目录

可以使用Path.Current更改进程的当前工作目录。

要快速将当前工作目录更改为某个路径,请使用changeDirectory(_:)方法:

1Path.userDesktop.changeDirectory {
2    print(Path.current)  // "/Users/nvzqz/Desktop"
3}

共同祖先目录

可以获得两个路径之间的共同祖先:

1print(Path.root.commonAncestor(.userHome))       // "/"
2print("~/Desktop"  <^> "~/Downloads")            // "~"
3print(.UserLibrary <^> .UserApplicationSupport)  // "/Users/nvzqz/Library"

+操作

追加两个路径并返回结果

1// ~/Documents/My Essay.docx
2let essay = Path.userDocuments + "My Essay.docx"
也可以把字符串拼接成路径
1let numberedFile: Path = "path/to/dir" + String(10// "path/to/dir/10"
+=操作

将右侧的路径添加到左侧路径。 也适用于String。

1var photos = Path.userPictures + "My Photos"  // ~/Pictures/My Photos
2photos += "../My Other Photos"                // ~/Pictures/My Photos/../My Other Photos
更多请参见开源代码主页。

相关开源代码

您还未登录,请先登录

热门帖子

最新帖子