import UIKit
class ViewController: UIViewController {
lazy var documentsPath:String={
let paths=NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)
return paths.first!
}()
}
extension ViewController{
override func viewDidLoad() {
super.viewDidLoad()
directoryTest()
fileTest()
}
}
//目录管理
extension ViewController{
func directoryTest(){
//检查目录是否存在,如果不存在,则创建目录
let path="\(documentsPath)/Data"
print(path)
if !directoryExistsAtPath(path){
createDirectoryAtPath(path)
directoryExistsAtPath(path)
}
//删除目录
deleteDirectoryAtPath(path)
//删除之后,再检查一次
directoryExistsAtPath(path)
}
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)
} catch{
print("create directory failed......")
}
}
func deleteDirectoryAtPath(path:String){
let fileManager=NSFileManager.defaultManager()
do{
try fileManager.removeItemAtPath(path)
}catch{
print("delete directory failed......")
}
}
}
//文件管理
extension ViewController{
func fileTest(){
//检查文件是否存在,如果不存在,则创建文件
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)
}
func deleteFileAtPath(path:String){
let fileManager=NSFileManager.defaultManager()
do{
try fileManager.removeItemAtPath(path)
}catch{
print("delete directory failed......")
}
}
}