NSFileManager

1 篇文章 / 0 new
author
NSFileManager
NSFileManager 是一個檔案管理內, 常用功能如下
var fileManager = NSFileManager.defaultManager()
►   取得目錄下所有檔案
//假設用戶文檔下有如下檔和資料夾[test1.txt,fold1/test2.txt]
let manager = NSFileManager.defaultManager()
let urlForDocument = manager.URLsForDirectory( NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
let url = urlForDocument[0] as NSURL
 
//(1)對指定路徑執行淺搜索,返回指定目錄路徑下的檔、子目錄及符號連結的清單
let contentsOfPath = try? manager.contentsOfDirectoryAtPath(url.path!)
//contentsOfPath:Optional([fold1, test1.txt])
print("contentsOfPath: \(contentsOfPath)")
 
//(2)類似上面的,對指定路徑執行淺搜索,返回指定目錄路徑下的檔、子目錄及符號連結的清單
let contentsOfURL = try? manager.contentsOfDirectoryAtURL(url, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles);
//contentsOfURL:Optional([file://Users/.../Application/.../Documents/fold1/,
// file://Users/.../Application/.../Documents/test1.txt])
print("contentsOfURL: \(contentsOfURL)")
 
//(3)深度遍歷,會遞迴遍歷子資料夾(但不會遞迴符號連結)
let enumeratorAtPath = manager.enumeratorAtPath(url.path!)
//enumeratorAtPath:Optional([fold1, fold1/test2.txt, test1.txt])
print("enumeratorAtPath: \(enumeratorAtPath?.allObjects)")
 
//(4)類似上面的,深度遍歷,會遞迴遍歷子資料夾(但不會遞迴符號連結)
let enumeratorAtURL = manager.enumeratorAtURL(url, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler:nil)
//contentsOfURL:Optional([file://Users/.../Application/.../Documents/fold1/,
// file://Users/.../Application/.../Documents/fold1/test2.txt,
// file://Users/.../Application/.../Documents/test1.txt])
print("enumeratorAtURL: \(enumeratorAtURL?.allObjects)")
 
//(5)深度遍歷,會遞迴遍歷子資料夾(包括符號連結,所以要求性能的話用enumeratorAtPath)
let subPaths = manager.subpathsAtPath(url.path!)
//subPaths:Optional([fold1, fold1/test2.txt, test1.txt])
print("subPaths: \(subPaths)")
► 判斷檔或資料夾是否存在
let fileManager = NSFileManager.defaultManager()
let filePath:String = NSHomeDirectory() + "/Documents/test.txt"
var exist = fileManager.fileExistsAtPath(filePath)
► 建立資料夾
let myDirectory:String = NSHomeDirectory() + "/Documents/myFolder/Files"
let fileManager = NSFileManager.defaultManager()
//withIntermediateDirectories為ture表示路徑中間如果有不存在的資料夾都會建立
try! fileManager.createDirectoryAtPath(myDirectory,
    withIntermediateDirectories: true, attributes: nil)
func createFolder(name:String,baseUrl:NSURL){
    let manager = NSFileManager.defaultManager()
    let folder = baseUrl.URLByAppendingPathComponent(name, isDirectory: true)
    print("資料夾: \(folder)")
    let exist = manager.fileExistsAtPath(folder.path!)
    if !exist {
        try! manager.createDirectoryAtURL(folder, withIntermediateDirectories: true, attributes: nil)
    }
}
 
//在文檔目錄下新建folder目錄
let manager = NSFileManager.defaultManager()
let urlForDocument = manager.URLsForDirectory( NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
let url = urlForDocument[0] as NSURL
createFolder("folder", baseUrl: url)
► 將資料存入檔案 : 可以通過writeToFile方法,可以創建檔並將物件寫入,物件包括String,NSString,UIImage,NSArray,NSDictionary等
//把String保存到檔
let filePath:String = NSHomeDirectory() + "/Documents/hangge.txt"
let info = "歡迎來到 swift"
try! info.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding)
//把圖片保存到檔路徑下
let filePath:String = NSHomeDirectory() + "/Documents/hangge.png"
let image = UIImage(named: "apple.png")
let data:NSData = UIImagePNGRepresentation(image!)!
data.writeToFile(filePath, atomically: true)
把NSArray保存到文件路径下
let array = NSArray(objects: "aaa","bbb","ccc")
let filePath:String = NSHomeDirectory() + "/Documents/array.plist"
array.writeToFile(filePath, atomically: true)
把NSDictionary保存到文件路径下
let dictionary = NSDictionary(objects: ["111","222"], forKeys: ["aaa","bbb"])
let filePath:String = NSHomeDirectory() + "/Documents/dictionary.plist"
dictionary.writeToFile(filePath, atomically: true)
► 建立檔案
func createFile(name:String,fileBaseUrl:NSURL){
    let manager = NSFileManager.defaultManager()
 
    let file = fileBaseUrl.URLByAppendingPathComponent(name)
    print("文件: \(file)")
    let exist = manager.fileExistsAtPath(file.path!)
    if !exist {
        let data = NSData(base64EncodedString:"aGVsbG8gd29ybGQ=",options:.IgnoreUnknownCharacters)
        let createSuccess = manager.createFileAtPath(file.path!,contents:data,attributes:nil)
        print("檔創建結果: \(createSuccess)")
    }
}
 
//在目錄下新建 test.txt
let manager = NSFileManager.defaultManager()
let urlForDocument = manager.URLsForDirectory( NSSearchPathDirectory.DocumentDirectory,
    inDomains:NSSearchPathDomainMask.UserDomainMask)
let url = urlForDocument[0] as NSURL
createFile("test.txt", fileBaseUrl: url)
//createFile("folder/new.txt", fileBaseUrl: url)
► 複製檔案
//方法1
let fileManager = NSFileManager.defaultManager()
let homeDirectory = NSHomeDirectory()
let srcUrl = homeDirectory + "/Documents/hangge.txt"
let toUrl = homeDirectory + "/Documents/copyed.txt"
try! fileManager.copyItemAtPath(srcUrl, toPath: toUrl)
 
//方法2
// 定位到使用者文檔目錄
let manager = NSFileManager.defaultManager()
let urlForDocument = manager.URLsForDirectory( NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
let url = urlForDocument[0] as NSURL
 
// 將test.txt檔拷貝到文檔目錄根目錄下的copyed.txt文件
let srcUrl = url.URLByAppendingPathComponent("test.txt")
let toUrl = url.URLByAppendingPathComponent("copyed.txt")
try! manager.copyItemAtURL(srcUrl, toURL: toUrl)
► 搬移檔案
//方法1
let fileManager = NSFileManager.defaultManager()
let homeDirectory = NSHomeDirectory()
let srcUrl = homeDirectory + "/Documents/hangge.txt"
let toUrl = homeDirectory + "/Documents/moved"
try! fileManager.moveItemAtPath(srcUrl, toPath: toUrl)
 
//方法2
// 定位到使用者文檔目錄
let manager = NSFileManager.defaultManager()
let urlForDocument = manager.URLsForDirectory( NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
let url = urlForDocument[0] as NSURL
 
let srcUrl = url.URLByAppendingPathComponent("test.txt")
let toUrl = url.URLByAppendingPathComponent("copyed.txt")
// 移動srcUrl中的文件(test.txt)到toUrl中(copyed.txt)
try! manager.moveItemAtURL(srcUrl, toURL: toUrl)
► 刪除資料
//方法1
let fileManager = NSFileManager.defaultManager()
let homeDirectory = NSHomeDirectory()
let srcUrl = homeDirectory + "/Documents/hangge.txt"
try! fileManager.removeItemAtPath(srcUrl)
 
//方法2
// 定位到使用者文檔目錄
let manager = NSFileManager.defaultManager()
let urlForDocument = manager.URLsForDirectory( NSSearchPathDirectory.DocumentDirectory,
    inDomains:NSSearchPathDomainMask.UserDomainMask)
let url = urlForDocument[0] as NSURL
 
let toUrl = url.URLByAppendingPathComponent("copyed.txt")
// 刪除文檔根目錄下的toUrl路徑的檔(copyed.txt文件)
try! manager.removeItemAtURL(toUrl)
► 刪除目錄下所有檔案
//方法1:獲取所有檔,然後遍歷刪除
let fileManager = NSFileManager.defaultManager()
let myDirectory = NSHomeDirectory() + "/Documents/Files"
let fileArray:[AnyObject]? = fileManager.subpathsAtPath(myDirectory)
for fn in fileArray!{
    try! fileManager.removeItemAtPath(myDirectory + "/\(fn)")
}
 
//方法2:刪除目錄後重新創建該目錄
let fileManager = NSFileManager.defaultManager()
let myDirectory = NSHomeDirectory() + "/Documents/Files"
try! fileManager.removeItemAtPath(myDirectory)
try! fileManager.createDirectoryAtPath(myDirectory, withIntermediateDirectories: true, attributes: nil)
► 讀取檔案
let manager = NSFileManager.defaultManager()
let urlsForDocDirectory = manager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
let docPath:NSURL = urlsForDocDirectory[0] as NSURL
let file = docPath.URLByAppendingPathComponent("test.txt")
 
//方法1
let readHandler = try! NSFileHandle(forReadingFromURL:file)
let data = readHandler.readDataToEndOfFile()
let readString = NSString(data: data, encoding: NSUTF8StringEncoding)
print("檔內容: \(readString)")
 
//方法2
let data = manager.contentsAtPath(file.path!)
let readString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("檔內容: \(readString)")
► 寫入資料
let manager = NSFileManager.defaultManager()
let urlsForDocDirectory = manager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
let docPath:NSURL = urlsForDocDirectory[0] as NSURL
let file = docPath.URLByAppendingPathComponent("test.txt")
 
let string = "添加一些文字到檔末尾"
let appendedData = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
let writeHandler = try? NSFileHandle(forWritingToURL:file)
writeHandler!.seekToEndOfFile()
writeHandler!.writeData(appendedData!)
► 權限判斷
let manager = NSFileManager.defaultManager()
let urlsForDocDirectory = manager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
let docPath:NSURL = urlsForDocDirectory[0] as NSURL
let file = docPath.URLByAppendingPathComponent("test.txt")
 
let readable = manager.isReadableFileAtPath(file.path!)
print("可讀: \(readable)")
let writeable = manager.isWritableFileAtPath(file.path!)
print("可寫: \(writeable)")
let executable = manager.isExecutableFileAtPath(file.path!)
print("可執行: \(executable)")
let deleteable = manager.isDeletableFileAtPath(file.path!)
print("可刪除: \(deleteable)")
► 檔案屬性(創建時間,修改時間,檔大小,檔案類型等資訊)
let manager = NSFileManager.defaultManager()
let urlsForDocDirectory = manager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory,
    inDomains:NSSearchPathDomainMask.UserDomainMask)
let docPath:NSURL = urlsForDocDirectory[0] as NSURL
let file = docPath.URLByAppendingPathComponent("test.txt")
 
let attributes = try? manager.attributesOfItemAtPath(file.path!) //結果為AnyObject類型
print("attributes: \(attributes!)")
► 檔案/資料夾比較
let manager = NSFileManager.defaultManager()
let urlsForDocDirectory = manager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory,
    inDomains:NSSearchPathDomainMask.UserDomainMask)
let docPath:NSURL = urlsForDocDirectory[0] as NSURL
let contents = try! manager.contentsOfDirectoryAtPath(docPath.path!)
 
//下面比較前面兩個檔是否內容相同(該方法也可以用來比較目錄)
let count = contents.count
if count > 1 {
    let path1 = docPath.path! + "/" + (contents[0] as String)
    let path2 = docPath.path! + "/" + (contents[1] as String)
    let equal = manager.contentsEqualAtPath(path1,andPath:path2)
    print("比較結果: \(equal)")
}
Free Web Hosting