文件操作
NSFileManager
1.NSFileManager 專門負(fù)責(zé)文件/文件夾的管理操作,包括創(chuàng)建/刪除/移動/拷貝
2.NSFileManager 是一個單例類
3.NSFileManager 中所有的功能是通過變量型方法提供的
聲明一個文件操作的路徑
let path = "/Users/qianfeng/Desktop/iOS學(xué)習(xí)/swift語言階段/第四周/day5-/實(shí)驗(yàn)文件夾"
1.獲取單例對象
let fileManager = NSFileManager.defaultManager()
2.淺度遍歷
函數(shù)原型:public func contentsOfDirectoryAtPath(path: String) throws -> [String]
參數(shù):需要遍歷文件夾的路徑
功能:獲取指定路徑文件夾下的所有文件或文件夾的相對路徑(相對于指定文件夾來說)->獲取指定文件夾下所有文件或文件夾的名字;不能獲取當(dāng)前目錄下子目錄中的內(nèi)容
try? 如果后面有異常那么函數(shù)返回值是nil;如果沒有異常返回值就是函數(shù)返回值類型的值
let contents = try? fileManager.contentsOfDirectoryAtPath(path)
if let content2 = contents {
print("淺度遍歷結(jié)果:\(content2)")
}else{
print("有異常")
}
3.深度遍歷
函數(shù)原型: public func subpathsOfDirectoryAtPath(path: String) throws -> [String]
參數(shù):需要遍歷文件夾路徑
功能:獲取指定路徑文件夾下的所有文件或文件夾的相對路徑(相對于指定文件夾來說)->能獲取當(dāng)前目錄下所有的子目錄的內(nèi)容
try? 如果后面有異常那么函數(shù)返回值是nil;如果沒有異常返回值就是函數(shù)返回值類型的值
let subContents = try? fileManager.subpathsOfDirectoryAtPath(path)
if subContents != nil {
print("深度遍歷結(jié)果:\(subContents!)")
}else{
print("有異常")
}
4.創(chuàng)建目錄
函數(shù)原型:public func createDirectoryAtPath(path: String, withIntermediateDirectories createIntermediates: Bool, attributes: [String : AnyObject]?) throws
參數(shù)1:需要創(chuàng)建目錄的路徑(注意:這個目錄必須是需要創(chuàng)建好的文件夾的目錄)
參數(shù)2:是否創(chuàng)建中間目錄(如果傳人true,會自動創(chuàng)建目錄中不存在的所有的中間目錄)
參數(shù)3:nil(創(chuàng)建的文件夾是默認(rèn)屬性)
do{ }catch{ } 異常處理函數(shù)
do{
try fileManager.createDirectoryAtPath(path+"/123/ddd", withIntermediateDirectories: true, attributes: nil)
}catch{
//如果獲取到do中調(diào)用的函數(shù)異常,就會執(zhí)行catch
print("創(chuàng)建目錄異常")
}
5.創(chuàng)建文件
函數(shù)原型:public func createFileAtPath(path: String, contents data: NSData?, attributes attr: [String : AnyObject]?) -> Bool
參數(shù)1:需要創(chuàng)建文件的路徑(路徑中必須拼接創(chuàng)建好的文件的名字)
參數(shù)2:需要在創(chuàng)建時給文件中寫入的數(shù)據(jù)(如果是nil就不寫數(shù)據(jù)到文件中)
參數(shù)3:文件屬性(傳nil是默認(rèn)屬性)
返回值:是否創(chuàng)建成功
功能:在指定位置創(chuàng)建一個文件,并且寫入指定數(shù)據(jù);如果文件已存在,創(chuàng)建的時候會覆蓋原來的文件
.txt 文件用來存儲文本,文本對應(yīng)程序中的字符串。這里寫入的數(shù)據(jù)應(yīng)該是字符串?dāng)?shù)據(jù)
NSDate 二進(jìn)制類型,在iOS或swift中所有和本地文件或者服務(wù)器進(jìn)行數(shù)據(jù)交流,必須以二進(jìn)制的形式進(jìn)行數(shù)據(jù)傳遞
let wirteStr = "勝利收發(fā)貨了客戶問人家了一個人加我我if交流環(huán)節(jié)收費(fèi)hi還是該符號沒我份呢林森浩"
將字符串轉(zhuǎn)換為NSDate
參數(shù):編碼方法(NSUTF8StringEncoding是中文編碼方式)
let data1 = wirteStr.dataUsingEncoding(NSUTF8StringEncoding)
let ret1 = fileManager.createFileAtPath(path+"/444.txt", contents: data1, attributes: nil)
if ret1 {
print("文件創(chuàng)建成功")
}else{
print("文件創(chuàng)建失敗")
}
將圖片文件/音頻/視頻文件轉(zhuǎn)化為二進(jìn)制文件
將本地文件轉(zhuǎn)化為二進(jìn)制
let vidio1 = NSData.init(contentsOfFile: "/Users/qianfeng/Desktop/iOS學(xué)習(xí)/swift語言階段/第一周牛眼睛/第三天/html/2-Resource/MovieTest.mp4")
let ret2 = fileManager.createFileAtPath(path+"/m.mp4", contents: vidio1, attributes: nil)
if ret2 {
print("文件創(chuàng)建成功")
}else{
print("文件創(chuàng)建失敗")
}
6.刪除文件/目錄
函數(shù)原型: public func removeItemAtPath(path: String) throws
函數(shù)原型里面有"throws"就要加"try"
參數(shù):需要刪除的文件或目錄的地址
do{
try fileManager.removeItemAtPath(path+"/bbb")
}catch{
print("刪除文件/目錄異常")
}
7.判斷文件或者目錄是否存在
函數(shù)原型;public func fileExistsAtPath(path: String) -> Bool
參數(shù):需要判斷的文件/目錄的路徑
返回值:判斷結(jié)果
let ret3 = fileManager.fileExistsAtPath(path)
if ret3 == true {
print("文件/目錄存在")
}else{
print("文件/目錄不存在")
}
8.判斷文件或者目錄是否存在,同時判斷是否是目錄
函數(shù)原型:fileExistsAtPath(path: String, isDirectory: UnsafeMutablePointer) -> Bool
參數(shù)1:需要判斷的文件/目錄的路徑
參數(shù)2:存儲是否是目錄的結(jié)果(需要傳入一個objeCBool類型的指針,對應(yīng)到swift中就是地址)
返回值:是否存在的結(jié)果
"&" 取地址的符號
var ret4: ObjCBool = ObjCBool(false)
let ret5 = fileManager.fileExistsAtPath(path+"/444.txt", isDirectory: &ret4)
//判斷是否存在
if ret5 {
print("文件/目錄存在")
//判斷是否是目錄
if ret4 {
print("是目錄")
}else{
print("不是目錄")
}
}else{
print("文件/目錄不存在")
}
9.獲取文件/目錄的屬性
函數(shù)原型: public func attributesOfItemAtPath(path: String) throws -> [String : AnyObject]
參數(shù):獲取文件/目錄的路徑
let attributes = try? fileManager.attributesOfItemAtPath(path)
if attributes != nil {
print("屬性:\(attributes!)")
print(attributes!["NSFileCreationDate"]!)
}else{
print("獲取屬性異常")
}
10.文件/目錄的拷貝
函數(shù)原型:public func copyItemAtPath(srcPath: String, toPath dstPath: String) throws
參數(shù)1:源文件/目錄路徑
參數(shù)2:目的路徑(需要拼接拷貝成功后的文件名/目錄名)
do{
try fileManager.copyItemAtPath(path+"/444.txt", toPath: path+"/123/444.txt")
}catch{
print("拷貝異常")
}
11.文件/目錄的移動
函數(shù)原型:public func moveItemAtPath(srcPath: String, toPath dstPath: String) throws
參數(shù)1:源文件/目錄路徑
參數(shù)2:目的路徑(需要拼接移動成功后的文件名/目錄名)
do{
try fileManager.moveItemAtPath(path+"/m.mp4", toPath: path+"/123/mm.mp4")
}catch{
print("移動異常")
}
文件讀寫
NSFileHandle (文件代言人)
將文件和NSFileHandle對象關(guān)聯(lián)在一起后,對NSFileHandle對象進(jìn)行操作相當(dāng)于對文件本身進(jìn)行操作
let path = "/Users/qianfeng/Desktop/iOS學(xué)習(xí)/swift語言階段/第四周/day5-/實(shí)驗(yàn)文件夾/444.txt"
1.創(chuàng)建方式:
a.以讀的形式打開一個文件來創(chuàng)建這個文件對應(yīng)的NSFileHandle對象;只能通過NSFileHandle對象對文件進(jìn)行讀操作
參數(shù):與NSFileHandle對象關(guān)聯(lián)的文件路徑
let handle0 = NSFileHandle.init(forReadingAtPath: path)
var handle: NSFileHandle = NSFileHandle()
if let thandle = handle0{
handle = thandle
}else{
print("關(guān)聯(lián)失敗")
}
2.讀取指定長度的文件內(nèi)容
函數(shù)原型:public func readDataOfLength(length: Int) -> NSData
參數(shù):長度(單位:字節(jié))
let data2 = handle.readDataOfLength(200)
//將NSData轉(zhuǎn)換成字符串
let str2 = String.init(data: data2, encoding: NSUTF8StringEncoding)
print("指定長度\n:\(str2!)")
總結(jié):使用同一個文件句柄對象去多次讀取文件操作,每次讀取都是從上一次讀取到的位置接著往后讀取
3.讀取到文件尾
函數(shù)原型:public func readDataToEndOfFile() -> NSData
let data1 = handle.readDataToEndOfFile()
print(data1)
將NSData轉(zhuǎn)換成字符串
let str1 = String.init(data: data1, encoding: NSUTF8StringEncoding)
print("讀取到文件尾:\n\(str1!)")
4.定位讀寫進(jìn)度
將讀寫進(jìn)度定位到文件的最后
handle.seekToEndOfFile()
將讀寫進(jìn)度定位到指定位置
參數(shù):距離文件開始位置的偏移大?。? ->就是定位到文件開始位置)
handle.seekToFileOffset(0)
b.以寫的形式去創(chuàng)建文件句柄(只能通過文件句柄對象進(jìn)行寫操作)
let handleW = NSFileHandle.init(forWritingAtPath: path)
var handle2 = NSFileHandle()
if let thandle = handleW {
handle2 = thandle
}else{
print("寫關(guān)聯(lián)失敗")
}
1.將數(shù)據(jù)寫入文件中
函數(shù)原型:public func writeData(data: NSData)
參數(shù):需要寫入文件中的數(shù)據(jù)
功能:第一次寫的時候從文件的開始位置寫,會覆蓋原來位置上的數(shù)據(jù);多次進(jìn)行寫操作的時候,每次都是在上次寫入結(jié)束的位置接著寫
如果想要從文件尾開始寫數(shù)據(jù),只需要在寫之前將讀寫進(jìn)度定位到文件尾
handle2.seekToEndOfFile()? ? //默認(rèn)定位到文件尾
let str3 = "dfkikkkkkkkkkkkkkkkkkkkk"
let data3 = str3.dataUsingEncoding(NSUTF8StringEncoding)
handle2.writeData(data3!)
let str4 = "aaaaaaaaaaaaaaaaaa"
let data4 = str4.dataUsingEncoding(NSUTF8StringEncoding)
handle2.writeData(data4!)
2.清除文件內(nèi)容
參數(shù):清除文件后剩余的內(nèi)容的字節(jié)數(shù)。留的是文件前半部分內(nèi)容,從后往前清理。(0 ->全部清空)
handle2.truncateFileAtOffset(0)
練習(xí):
調(diào)用函數(shù)方式整理文件
let ret = GJFileManager.sortOutDirectory(path: "/Users/qianfeng/Desktop/iOS學(xué)習(xí)/swift語言階段/第四周/day5-文件操作/zuoye/homekwork")
class GJFileManager {
//函數(shù)功能:整理文件夾
//參數(shù):需要整理的文件夾的路徑
//返回值:文件夾整理是否成功
static func sortOutDirectory(path path: String) -> Bool {
let fileManager = NSFileManager.defaultManager()
//1.檢查路徑是否合法
var isDirectory:ObjCBool = ObjCBool(false)
//判斷當(dāng)前路徑下的文件/文件夾是否存在,并且判斷是否是目錄
let isExists = fileManager.fileExistsAtPath(path, isDirectory: &isDirectory)
if isExists {
if isDirectory {
//處理文件夾
self.dealDirectory(path: path)
return true
}else{
print("不是文件夾")
return false
}
}else{
print("路徑不存在")
return false
}
}
//處理文件夾
private static func dealDirectory(path path: String) {
let fileManager = NSFileManager.defaultManager()
//1.淺度遍歷文件夾,獲取文件夾中所有內(nèi)容
let contents = try! fileManager.contentsOfDirectoryAtPath(path)
print(contents)
//2.遍歷文件夾中的所有內(nèi)容
for fileName in contents {
print(fileName)
//判斷是否是文件夾
var isDirectory = ObjCBool(false)
//拼接出文件/文件夾路徑
let filePath = path+"/"+fileName
fileManager.fileExistsAtPath(filePath, isDirectory: &isDirectory)
//如果是文件夾
if isDirectory {
//創(chuàng)建文件夾DIR
do{
try fileManager.createDirectoryAtPath(path+"/DIR", withIntermediateDirectories: true, attributes: nil)
}catch{
print("文件夾已經(jīng)存在")
}
//將文件夾移動到DIR中
do {
try fileManager.moveItemAtPath(filePath, toPath: path+"/DIR"+"/"+fileName)
}catch{
print("移動失敗")
}
}else{
//如果是文件
//先取出文件的后綴
//1.找出“.”的位置
let index = fileName .rangeOfString(".")?.startIndex
//2.獲取后綴
let suffix = fileName.substringFromIndex(index!.successor())
//3.將后綴轉(zhuǎn)換為大寫字母
let upSuffix = suffix.uppercaseString
//4.創(chuàng)建對應(yīng)的文件夾
do{
try fileManager.createDirectoryAtPath(path+"/"+upSuffix, withIntermediateDirectories: true, attributes: nil)
}catch{
}
//5.移動文件
do{
try fileManager.moveItemAtPath(filePath, toPath: path+"/"+upSuffix+"/"+fileName)
}catch{
}
}
}
}
}