FileKit是一個(gè)簡單且可以使用表達(dá)式來管理文件的Swift框架。
示例代碼:
路徑
通過Path
結(jié)構(gòu)體創(chuàng)建路徑。
2 | let drive: Path = "/Volumes/Macintosh HD" |
3 | let file: Path = "~/Desktop/file\(1)" |
新建文件
可以通過在Path
上調(diào)用createFile()
來編寫空白文件。
1 | try Path( ".gitignore" ).createFile() |
新建目錄
可以通過在Path
上調(diào)用createDirectory()
來創(chuàng)建目錄。
1 | try Path( "~/Files" ).createDirectory() |
2 | try Path( "~/Books" ).createDirectory(withIntermediateDirectories: false) |
創(chuàng)建符號(hào)鏈接
可以通過在Path
上調(diào)用createSymlinkToPath(_:)
創(chuàng)建符號(hào)鏈接。
1 | try Path( "path/to/MyApp.app" ).symlinkFile(to: "~/Applications" ) |
2 | print(Path( "~/Applications/MyApp.app" ).exists) |
查找路徑
在桌面的5個(gè)層級(jí)目錄內(nèi)查找所有.txt后綴的文件。
1 | let textFiles = Path.userDesktop.find(searchDepth: 5 ) { path in |
2 | path.pathExtension == "txt" |
使用searchDepth
來指定查找的目錄層級(jí)。
迭代路徑
1 | for download in Path.userDownloads { |
2 | print( "Downloaded file: \(download)" ) |
當(dāng)前工作目錄
可以使用Path.Current
更改進(jìn)程的當(dāng)前工作目錄。
要快速將當(dāng)前工作目錄更改為某個(gè)路徑,請(qǐng)使用changeDirectory(_:)
方法:
1 | Path.userDesktop.changeDirectory { |
共同祖先目錄
可以獲得兩個(gè)路徑之間的共同祖先:
1 | print(Path.root.commonAncestor(.userHome)) |
2 | print( "~/Desktop" <^> "~/Downloads" ) |
3 | print(.UserLibrary <^> .UserApplicationSupport) |
+
操作
追加兩個(gè)路徑并返回結(jié)果
2 | let essay = Path.userDocuments + "My Essay.docx" |
也可以把字符串拼接成路徑
1 | let numberedFile: Path = "path/to/dir" + String( 10 ) |
+=
操作
將右側(cè)的路徑添加到左側(cè)路徑。 也適用于String。
1 | var photos = Path.userPictures + "My Photos" |
2 | photos += "../My Other Photos" |
更多請(qǐng)參見開源代碼主頁。