FileManager
IOS應用只能訪問自己應用目錄下的檔案。預設情況下,每個沙盒含有3個資料夾:Documents, Library 和 tmp。Library包含Caches、Preferences目錄。
let homeDir = NSHomeDirectory()
print("[home]: ", homeDir)
// all sub paths:
// "Documents",
// "Library",
// "Library/Caches/*",
// "Library/Preferences",
// "tmp"
let homeSubDirs = NSFileManager.defaultManager().subpathsAtPath(homeDir)
print("[home sub paths]", homeSubDirs!, homeSubDirs!.count)
// Document
let docDirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
print("[docment]: ", docDirs, docDirs.count)
// Library
let libDirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomainMask.UserDomainMask, true)
print("[library]: ", libDirs, libDirs.count)
fileManager = NSFileManager.defaultManager()
-
建立檔案:
fileManager.createFileAtPath
或
data.writeToFile(newFileWithPath, atomically: true, encoding: NSUTF8StringEncoding)
-
建立資料夾
fileManager.createDirectoryAtPath
-
檔案檢查
fileManager.fileExistsAtPath(filePath)
-
移動(重新命名)
fileManager.moveItemAtPath
-
拷貝
fileManager.copyItemAtPath
-
目錄下所有檔案(會遍歷到所有子目錄)
fileManager.subpathsAtPath
-
刪除檔案
fileManager.removeItemAtPath