先获得Documents路径
class ViewController: UIViewController { // MARK: - Properties lazy var documentsPath: String = { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) return paths.first! }() }
先实现目录的查询、创建与删除吧,⬇️检查目录是否存在⬇️
func directoryExistsAtPath(path: String) -> Bool { let fileManager = NSFileManager.defaultManager() let result = fileManager.fileExistsAtPath(path) if result { print("directory exists...") } else { print("directory not exists...") } return result }
⬇️创建目录⬇️
func createDirectoryAtPath(path: String) { let fileManager = NSFileManager.defaultManager() do { try fileManager.createDirectoryAtPath(path, withIntermediateDirectories: false, attributes: nil)//path:目录路径,withIntermediateDirectories:告诉系统上级目录是否存在,true表示需要创建多级目录,attributes:文件夹相关属性 } catch { print("create directory failed...") } }
⬇️删除目录⬇️
func deleteDirectoryAtPath(path: String) { let fileManager = NSFileManager.defaultManager() do { try fileManager.removeItemAtPath(path) } catch { print("delete directory failed...") } }
再来看看文件的相关操作,其实和目录大同小异
⬇️检查文件⬇️
func fileTest() { // ~/Documents/data.txt // 检查文件是否存在,如果不存在,则创建文件 let path = "(documentsPath)/data.txt" print(path) if !fileExistsAtPath(path) { createFileAtPath(path) fileExistsAtPath(path) } // 删除目录 deleteFileAtPath(path) // 删除之后,再检查一次 fileExistsAtPath(path) } func fileExistsAtPath(path: String) -> Bool { let fileManager = NSFileManager.defaultManager() let result = fileManager.fileExistsAtPath(path) if result { print("file exists...") } else { print("file not exists...") } return result }
⬇️创建文件⬇️
func createFileAtPath(path: String) { let fileManager = NSFileManager.defaultManager() fileManager.createFileAtPath(path, contents: nil, attributes: nil)//path代表文件路径,contents代表想要写入文件的内容,attributes代表文件相关属性 }
⬇️删除文件⬇️
func deleteFileAtPath(path: String) { let fileManager = NSFileManager.defaultManager() do { try fileManager.removeItemAtPath(path) } catch { print("delete directory failed...") } }
很容易比较出不同点在于创建和删除时的方法,创建目录是
.createDirectoryAtPath
创建文件是
.createFileAtPath
删除,呃,删除都是
.removeItemAtPath