IOS檔案操作

IOS檔案操作

遍歷某個資料夾的檔案

獲取當前路徑

let manager = FileManager.default
let urlForDocument = manager.urls(for: .documentDirectory, in:.userDomainMask)
let url = urlForDocument[0] as URL
print(url)


結果:
獲取當前路徑

對指定路徑進行淺搜尋,返回指定路徑下的檔案,子目錄和符號連結的列表

let contentsOfPath = try? manager.contentsOfDirectory(atPath: url.path)
print("contentsOfPath: \(contentsOfPath)")

有另外一種寫法

let contentsOfURL = try? manager.contentsOfDirectory(at: url,
includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
print("contentsOfURL: \(contentsOfURL)")

淺遍歷

深度遍歷,會遞迴遍歷子資料夾和子檔案(但不會遞迴符號連結)

let enumeratorAtPath = manager.enumerator(atPath: url.path)
print("enumeratorAtPath: \(enumeratorAtPath?.allObjects)")

深遍歷
深度遍歷,會遞迴遍歷子資料夾(但不會遞迴符號連結)

let enumeratorAtURL = manager.enumerator(at: url, includingPropertiesForKeys: nil,
options: .skipsHiddenFiles, errorHandler:nil)
print("enumeratorAtURL: \(enumeratorAtURL?.allObjects)")

深遍歷獲取全路徑

深度遍歷,會遞迴遍歷子資料夾(包括符號連結,所以要求效能的話用enumeratorAtPath)

let subPaths = manager.subpaths(atPath: url.path)
print("subPaths: \(subPaths)")

深度遍歷

判斷檔案或者資料夾是否存在

let fileManager = FileManager.default
let filePath:String = NSHomeDirectory()   "/Documents/hangge.txt"
let exist = fileManager.fileExists(atPath: filePath)

判斷檔案或者資料夾是否存在

建立資料夾

let myDirectory:String = NSHomeDirectory()   "/Documents/myFolder/Files"
let fileManager = FileManager.default
//withIntermediateDirectories為ture表示路徑中間如果有不存在的資料夾都會建立
try! fileManager.createDirectory(atPath: myDirectory,
withIntermediateDirectories: true, attributes: nil)

建立資料夾
可以看到建立之後的陣列中已經有了新的資料夾
第二種方法

func createFolder(name:String,baseUrl:NSURL){
let manager = FileManager.default
let folder = baseUrl.appendingPathComponent(name, isDirectory: true)
print("資料夾: \(folder)")
let exist = manager.fileExists(atPath: folder!.path)
if !exist {
try! manager.createDirectory(at: folder!, withIntermediateDirectories: true,
attributes: nil)
}
}
//在文件目錄下新建folder目錄
let manager = FileManager.default
let urlForDocument = manager.urls(for: .documentDirectory, in: .userDomainMask)
let url = urlForDocument[0] as NSURL
createFolder(name: "folder", baseUrl: url)

將物件寫入檔案

可以通過write(to:)方法,可以建立檔案並將物件寫入,物件包括String,NSString,UIImage,NSArray,NSDictionary等

把String儲存到檔案

 let filePath:String = NSHomeDirectory() "/Documents/password.txt"
let msg = "我是測試內容,就問你怕不怕"
try! msg.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)

把String儲存到檔案覆蓋的形式

把圖片儲存到路徑下

let filePath = NSHomeDirectory()   "/Documents/hangge.png"
let image = UIImage(named: "apple.png")
let data:Data = UIImagePNGRepresentation(image!)!
try? data.write(to: URL(fileURLWithPath: filePath))

這個實驗之後是可以的,但是這個圖片比較難搞定,所以暫時先不貼出來了

把NSArray寫在檔案路徑下

let array = NSArray(objects: "aaa","bbb","ccc")
let filePath:String = NSHomeDirectory()   "/Documents/array.plist"
array.write(toFile: filePath, atomically: true)

把NSArray寫在檔案中

把NSDirectionary儲存到檔案中

let dictionary:NSDictionary = ["Gold": "1st Place", "Silver": "2nd Place"]
let filePath:String = NSHomeDirectory()   "/Documents/dictionary.plist"
dictionary.write(toFile: filePath, atomically: true)

把NSDirectionary儲存到檔案中

建立檔案

 //在文件目錄下新建test.txt檔案
let manager = FileManager.default
let urlForDocument = manager.urls( for: .documentDirectory,
in:.userDomainMask)
let url = urlForDocument[0]
createFile(name:"test.txt", fileBaseUrl: url)
//建立檔案的方法
func createFile(name:String, fileBaseUrl:URL){
let manager = FileManager.default
let file = fileBaseUrl.appendingPathComponent(name)
print("檔案: \(file)")
let exist = manager.fileExists(atPath: file.path)
if !exist {
let data = Data(base64Encoded:"aGVsbG8gd29ybGQ=" ,options:.ignoreUnknownCharacters)
let createSuccess = manager.createFile(atPath: file.path,contents:data,attributes:nil)
print("檔案建立結果: \(createSuccess)")
}
}

建立檔案

複製檔案

let fileManager = FileManager.default
let homeDirectory = NSHomeDirectory()
let srcUrl = homeDirectory   "/Documents/hangge.txt"
let toUrl = homeDirectory   "/Documents/copyed.txt"
try! fileManager.copyItem(atPath: srcUrl, toPath: toUrl)

複製檔案
另一種方法

// 定位到使用者文件目錄
let manager = FileManager.default
let urlForDocument = manager.urls( for:.documentDirectory, in:.userDomainMask)
let url = urlForDocument[0]
// 將test.txt檔案拷貝到文件目錄根目錄下的copyed.txt檔案
let srcUrl = url.appendingPathComponent("test.txt")
let toUrl = url.appendingPathComponent("copyed.txt")
try! manager.copyItem(at: srcUrl, to: toUrl)

移動檔案

let fileManager = FileManager.default
let homeDirectory = NSHomeDirectory()
let srcUrl = homeDirectory   "/Documents/hangge.txt"
let toUrl = homeDirectory   "/Documents/moved/hangge.txt"
try! fileManager.moveItem(atPath: srcUrl, toPath: toUrl)

另外一種方法

// 定位到使用者文件目錄
let manager = FileManager.default
let urlForDocument = manager.urls( for: .documentDirectory, in:.userDomainMask)
let url = urlForDocument[0]
let srcUrl = url.appendingPathComponent("test.txt")
let toUrl = url.appendingPathComponent("copyed.txt")
// 移動srcUrl中的檔案(test.txt)到toUrl中(copyed.txt)
try! manager.moveItem(at: srcUrl, to: toUrl)

刪除檔案

let fileManager = FileManager.default
let homeDirectory = NSHomeDirectory()
let srcUrl = homeDirectory   "/Documents/hangge.txt"
try! fileManager.removeItem(atPath: srcUrl)

另一種方法

// 定位到使用者文件目錄
let manager = FileManager.default
let urlForDocument = manager.urls(for: .documentDirectory, in:.userDomainMask)
let url = urlForDocument[0]
let toUrl = url.appendingPathComponent("copyed.txt")
// 刪除文件根目錄下的toUrl路徑的檔案(copyed.txt檔案)
try! manager.removeItem(at: toUrl)

刪除目錄下所有的檔案

let fileManager = FileManager.default
let myDirectory = NSHomeDirectory()   "/Documents/Files"
let fileArray = fileManager.subpaths(atPath: myDirectory)
for fn in fileArray!{
try! fileManager.removeItem(atPath: myDirectory   "/\(fn)")
}

刪除目錄後,再建立該目錄

let fileManager = FileManager.default
let myDirectory = NSHomeDirectory()   "/Documents/Files"
try! fileManager.removeItem(atPath: myDirectory)
try! fileManager.createDirectory(atPath: myDirectory, withIntermediateDirectories: true,
attributes: nil)

讀取檔案

let manager = FileManager.default
let urlsForDocDirectory = manager.urls(for: .documentDirectory, in:.userDomainMask)
let docPath = urlsForDocDirectory[0]
let file = docPath.appendingPathComponent("test.txt")
//方法1
let readHandler = try! FileHandle(forReadingFrom:file)
let data = readHandler.readDataToEndOfFile()
let readString = String(data: data, encoding: String.Encoding.utf8)
print("檔案內容: \(readString)")
//方法2
let data2 = manager.contents(atPath: file.path)
let readString2 = String(data: data2!, encoding: String.Encoding.utf8)
print("檔案內容: \(readString2)")

讀取檔案

在任意位置寫入資料

let manager = FileManager.default
let urlsForDocDirectory = manager.urls(for:.documentDirectory, in:.userDomainMask)
let docPath = urlsForDocDirectory[0]
let file = docPath.appendingPathComponent("test.txt")
let string = "新增一些文字到檔案末尾"
let appendedData = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
let writeHandler = try? FileHandle(forWritingTo:file)
writeHandler!.seekToEndOfFile()
writeHandler!.write(appendedData!)

在任意位置寫入資料

檔案許可權判斷

let manager = FileManager.default
let urlForDocument = manager.urls(for: .documentDirectory, in:.userDomainMask)
let docPath = urlForDocument[0]
let file = docPath.appendingPathComponent("test.txt")
let readable = manager.isReadableFile(atPath: file.path)
print("可讀: \(readable)")
let writeable = manager.isWritableFile(atPath: file.path)
print("可寫: \(writeable)")
let executable = manager.isExecutableFile(atPath: file.path)
print("可執行: \(executable)")
let deleteable = manager.isDeletableFile(atPath: file.path)
print("可刪除: \(deleteable)")

檔案許可權判斷

獲取檔案屬性(建立時間,修改時間,檔案大小,檔案型別等資訊

let manager = FileManager.default
let urlForDocument = manager.urls(for: .documentDirectory, in:.userDomainMask)
let docPath = urlForDocument[0]
let file = docPath.appendingPathComponent("test.txt")
let attributes = try? manager.attributesOfItem(atPath: file.path) //結果為Dictionary型別
print("attributes: \(attributes!)")

獲取檔案屬性
感覺內容太多,不清晰,我們可以拆分一下

print("建立時間:\(attributes![FileAttributeKey.creationDate]!)")
print("修改時間:\(attributes![FileAttributeKey.modificationDate]!)")
print("檔案大小:\(attributes![FileAttributeKey.size]!)")

檔案屬性