iOS FileManager使用

在iOS應(yīng)用開發(fā)的過程中,很多時(shí)候要用到數(shù)據(jù)存儲,將數(shù)據(jù)存儲在磁盤中。FileManager在存儲的過程中就起到非常重要的作用含懊,文件的管理都離不開它身冬,這邊文章從使用上簡單講一些常見用法衅胀。
寫在前面:代碼中的fileManeger,mainPath具體代碼
  private let fileManeger = FileManager.default
  private let mainPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last ?? ""

一酥筝、新增文件/文件夾滚躯,以及數(shù)據(jù)寫入

    //MARK: 新建文件夾
    func createFolder(with folderName:String) -> Bool{
        
        let folderPath = mainPath + folderName
        if !fileManeger.fileExists(atPath: folderPath){
            do {
                //attributes:用來設(shè)置文件夾的一些屬性(只讀,讀寫等)
                try fileManeger.createDirectory(at: URL(fileURLWithPath: folderPath), withIntermediateDirectories: true, attributes: nil)
            } catch {
                print("創(chuàng)建失敽俑琛掸掏!")
                return false
            }
        }else{
            print("已存在")
        }
        return true
    }
    //MARK: 新建文件
    func createNewFile(with filePath:String ,txt:String) -> Bool{
        let txtfilePath = mainPath + filePath
        //這里以txt文本為例,也可寫入其他類型文件
        let fileData = txt.data(using: String.Encoding.utf8)
    
        if !fileManeger.fileExists(atPath: txtfilePath){
            return self.writeDataToFilePath(with: txtfilePath, fileData: fileData)
        }else{
            print("已存在")
            return false
        }
    }
    //覆蓋數(shù)據(jù)宙帝,推薦使用replaceItemAt(originalItemURL: URL, withItemAt: URL, backupItemName: String, options: options)
    //或replaceItemAt(originalItemURL: url, withItemAt: url)
    func recoveryFile(with filePath:String ,txt:String) -> Bool{
        let txtfilePath = mainPath + filePath
        //這里以txt文本為例丧凤,也可寫入其他類型文件
        let fileData = txt.data(using: String.Encoding.utf8)
    
        if fileManeger.fileExists(atPath: txtfilePath){
            return self.writeDataToFilePath(with: txtfilePath, fileData: fileData)
        }else{
            print("文件路徑不存在")
            return false
        }
    }
    
    func writeDataToFilePath(with filePath:String ,fileData:Data?) -> Bool{
        //寫入數(shù)據(jù)也可以使用:fileData?.write(to: <#T##URL#>),attributes:用來設(shè)置文件的一些屬性(只讀步脓,讀寫等)
        return fileManeger.createFile(atPath: filePath, contents: fileData, attributes: nil)
    }

二愿待、刪除文件/文件夾

    //MARK: 刪除文件夾
    func removeFolder(with folderName:String) -> Bool{
        
        let folderPath = mainPath + folderName
        if fileManeger.fileExists(atPath: folderPath){
            do {
                try fileManeger.removeItem(atPath: folderPath)
            } catch {
                print("刪除失敽坡荨!")
                return false
            }
        }else{
            print("路徑不存在")
            return false
        }
        return true
    }
    //MARK: 刪除文件
    func removeFile(with filePath:String) -> Bool{
        let txtfilePath = mainPath + filePath

        if fileManeger.fileExists(atPath: txtfilePath){
            do {
                try fileManeger.removeItem(atPath: txtfilePath)
            } catch {
                print("刪除失斎越摹要出!")
                return false
            }
        }else{
            print("路徑不存在")
            return false
        }
        return true
    }

三、讀取文件夾下目錄农渊,及文件數(shù)據(jù)

    //MARK:查看文件列表
    func loadFileList(with path:String) -> [String]?{
        let folderPath = mainPath + path
        if fileManeger.fileExists(atPath: folderPath){
            //subpathsOfDirectory(atPath: ) 可以查看完整詳細(xì)的子路徑 如:["test", "test/The only .txt"]
           return fileManeger.subpaths(atPath: folderPath)
        }else{
           return nil
        }
    }

    //MARK:加載文件內(nèi)容
    func loadFileData(with path:String) ->Data?{
        let filePath = mainPath + path
        if fileManeger.fileExists(atPath: filePath){
            do {
               let fileData = try Data(contentsOf: URL(fileURLWithPath: filePath))
                return fileData
            } catch  {
                print("加載失敗")
                return nil
            }
        }
        print("路徑不存在")
        return nil
    }

四患蹂、復(fù)制或移動文件/文件夾

    //復(fù)制和移動,是基于兩個文件路徑來操作的砸紊,所以兩個文件都需要存在传于。
    //MARK: 復(fù)制文件
    func copyFile(from oldPath:String,to newPath:String){
        let oldFilePath = mainPath + oldPath
        let newFilePath = mainPath + newPath
        
        if fileManeger.fileExists(atPath: oldFilePath) && fileManeger.fileExists(atPath: newFilePath){
            do {
                try fileManeger.copyItem(atPath: oldFilePath, toPath: newFilePath)
            } catch {
                print("文件復(fù)制失敗醉顽!")
            }
        }else{
            print("文件路徑不存在")
        }
        
    }
    //MARK: 移動文件
    func moveFile(from oldPath:String,to newPath:String){
        let oldFilePath = mainPath + oldPath
        let newFilePath = mainPath + newPath
        
        if fileManeger.fileExists(atPath: oldFilePath) && fileManeger.fileExists(atPath: newFilePath){
            do {
                try fileManeger.moveItem(atPath: oldFilePath, toPath: newFilePath)
            } catch {
                print("文件移動失敻窳恕!")
            }
        }else{
            print("文件路徑不存在")
        }
    }

demo地址:本地文件管理

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末徽鼎,一起剝皮案震驚了整個濱河市盛末,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌否淤,老刑警劉巖悄但,帶你破解...
    沈念sama閱讀 218,941評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異石抡,居然都是意外死亡檐嚣,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評論 3 395
  • 文/潘曉璐 我一進(jìn)店門啰扛,熙熙樓的掌柜王于貴愁眉苦臉地迎上來嚎京,“玉大人,你說我怎么就攤上這事隐解“暗郏” “怎么了?”我有些...
    開封第一講書人閱讀 165,345評論 0 356
  • 文/不壞的土叔 我叫張陵煞茫,是天一觀的道長帕涌。 經(jīng)常有香客問我,道長续徽,這世上最難降的妖魔是什么蚓曼? 我笑而不...
    開封第一講書人閱讀 58,851評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮钦扭,結(jié)果婚禮上纫版,老公的妹妹穿的比我還像新娘。我一直安慰自己客情,他們只是感情好其弊,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,868評論 6 392
  • 文/花漫 我一把揭開白布会涎。 她就那樣靜靜地躺著,像睡著了一般瑞凑。 火紅的嫁衣襯著肌膚如雪末秃。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,688評論 1 305
  • 那天籽御,我揣著相機(jī)與錄音练慕,去河邊找鬼。 笑死技掏,一個胖子當(dāng)著我的面吹牛铃将,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播哑梳,決...
    沈念sama閱讀 40,414評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼劲阎,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了鸠真?” 一聲冷哼從身側(cè)響起悯仙,我...
    開封第一講書人閱讀 39,319評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎吠卷,沒想到半個月后锡垄,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,775評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡祭隔,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年货岭,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片疾渴。...
    茶點(diǎn)故事閱讀 40,096評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡千贯,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出搞坝,到底是詐尸還是另有隱情搔谴,我是刑警寧澤,帶...
    沈念sama閱讀 35,789評論 5 346
  • 正文 年R本政府宣布瞄沙,位于F島的核電站己沛,受9級特大地震影響慌核,放射性物質(zhì)發(fā)生泄漏距境。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,437評論 3 331
  • 文/蒙蒙 一垮卓、第九天 我趴在偏房一處隱蔽的房頂上張望垫桂。 院中可真熱鬧,春花似錦粟按、人聲如沸诬滩。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽疼鸟。三九已至后控,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間空镜,已是汗流浹背浩淘。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評論 1 271
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留吴攒,地道東北人张抄。 一個月前我還...
    沈念sama閱讀 48,308評論 3 372
  • 正文 我出身青樓,卻偏偏與公主長得像洼怔,于是被迫代替她去往敵國和親署惯。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,037評論 2 355

推薦閱讀更多精彩內(nèi)容