FileKit是一个简单且可以使用表达式来管理文件的Swift框架。
示例代码:
路径
通过Path结构体创建路径。
let home = Path("~")
let drive: Path = "/Volumes/Macintosh HD"
let file: Path = "~/Desktop/file\(1)"
新建文件
可以通过在Path上调用createFile()来编写空白文件。
try Path(".gitignore").createFile()
新建目录
可以通过在Path上调用createDirectory()来创建目录。
try Path("~/Files").createDirectory()
try Path("~/Books").createDirectory(withIntermediateDirectories: false)
创建符号链接
可以通过在Path上调用createSymlinkToPath(_:)创建符号链接。
try Path("path/to/MyApp.app").symlinkFile(to: "~/Applications")
print(Path("~/Applications/MyApp.app").exists) // true
查找路径
在桌面的5个层级目录内查找所有.txt后缀的文件。
let textFiles = Path.userDesktop.find(searchDepth: 5) { path in
path.pathExtension == "txt"
}
使用searchDepth来指定查找的目录层级。
迭代路径
for download in Path.userDownloads {
print("Downloaded file: \(download)")
}
当前工作目录
可以使用Path.Current更改进程的当前工作目录。
要快速将当前工作目录更改为某个路径,请使用changeDirectory(_:)方法:
Path.userDesktop.changeDirectory {
print(Path.current) // "/Users/nvzqz/Desktop"
}
共同祖先目录
可以获得两个路径之间的共同祖先:
print(Path.root.commonAncestor(.userHome)) // "/"
print("~/Desktop" <^> "~/Downloads") // "~"
print(.UserLibrary <^> .UserApplicationSupport) // "/Users/nvzqz/Library"
+操作
追加两个路径并返回结果
// ~/Documents/My Essay.docx let essay = Path.userDocuments + "My Essay.docx"也可以把字符串拼接成路径
let numberedFile: Path = "path/to/dir" + String(10) // "path/to/dir/10"
+=操作
将右侧的路径添加到左侧路径。 也适用于String。
var photos = Path.userPictures + "My Photos" // ~/Pictures/My Photos photos += "../My Other Photos" // ~/Pictures/My Photos/../My Other Photos更多请参见开源代码主页。