Swift常用路徑及FileManager相關(guān)操作

本文提供獲取路徑的兩種方法界弧,返回的類型都是String插爹,還有一種獲取路徑的方法返回的是URL扫步,FileManager也提供了通過(guò)URL操作文件的相關(guān)方法俭茧,和通過(guò)pathString操作的方法基本是一一對(duì)應(yīng),感興趣的同學(xué)可以對(duì)下面的代碼進(jìn)行替換碌尔,使用URL作為路徑的返回類型和FileManager函數(shù)的參數(shù)操作相關(guān)文件捏萍。

1.常用獲取路徑方法

enum AppDirectories {
    case documents
    case library
    case libraryCaches
    case temp
    case customPath(path: String)
}
// 本文提供了兩種獲取路徑的方法系冗,返回類型是String绢记,還有一種獲取路徑的方法返回的是URL扁达,F(xiàn)ileManager也提供了通過(guò)URL操作文件的相關(guān)方法,和通過(guò)pathString操作的方法基本是一一對(duì)應(yīng)庭惜,感興趣的同學(xué)可以對(duì)下面的代碼進(jìn)行替換罩驻,使用URL作為路徑的返回類型和函數(shù)的參數(shù)操作文件穗酥。
/// MARK: - 獲取路徑 以下兩種方法都可以
struct FilePathUtils {
    //document
    static func documentsDirectoryPath() -> String {
//        return NSSearchPathForDirectoriesInDomains(.userDirectory, .userDomainMask, true).first!
        return NSHomeDirectory().appending("/Documents")
    }

    //library
    static func libraryDirectoryPath() -> String {
//        return NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first!
        return NSHomeDirectory().appending("/Library")
    }

    //temp
    static func tempDirectoryPath() -> String {
//       return NSTemporaryDirectory()
        return NSHomeDirectory().appending("/tmp")
    }

    //Library/Caches
    static func librayCachesPath() -> String {
//        return NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
        return NSHomeDirectory().appending("/Library/Caches")
    }

    //根據(jù)枚舉值返回不同的url
    static func setupFilePath(directory: AppDirectories, name: String) -> String {
        return getPath(for: directory) + name
    }

    private static func getPath(for directory: AppDirectories) -> String {
        switch directory {
        case .documents:
            return documentsDirectoryPath()
        case .libraryCaches:
            return librayCachesPath()
        case .library:
            return libraryDirectoryPath()
        case .temp:
            return tempDirectoryPath()
        case .customPath(let path):
            return path
        }
    }
}

2.文件操作的相關(guān)方法

/// MARK: - 文件操作
struct FileUtils {

    // MARK: - 創(chuàng)建文件
    static func createFolder(basePath: AppDirectories, folderName: String, createIntermediates: Bool = true, attributes: [FileAttributeKey: Any]? = nil) -> Bool {
        let filePath = FilePathUtils.setupFilePath(directory: basePath, name: folderName)
        let  fileManager = FileManager.default
        do {
            try fileManager.createDirectory(atPath: filePath, withIntermediateDirectories: createIntermediates, attributes: attributes)
            return true
        } catch {
            return false
        }
    }

    // MARK: - 寫入文件
    // options: 默認(rèn)先創(chuàng)建一個(gè)臨時(shí)文件护赊,直到文件內(nèi)容寫入成功再導(dǎo)入到目標(biāo)文件里。 如果為NO砾跃,則直接寫入目標(biāo)文件里骏啰。
    static func writeFile(content: Data, filePath: String, options: Data.WritingOptions = []) -> Bool {
        do {
            try content.write(to: URL(string: filePath)!, options: options)
            return true
        } catch {
            return false
        }
    }

    // MARK: - 讀取文件
    static func readFile(filePath: String) -> Data? {
        let fileContents = FileManager.default.contents(atPath: filePath)
        if fileContents?.isEmpty == false {
            return fileContents
        } else {
            return nil
        }
    }

    // MARK: - 刪除文件
    static func deleteFile(filePath: String) -> Bool {
        do {
            try FileManager.default.removeItem(atPath: filePath)
            return true
        } catch {
            return false
        }
    }

    // MARK: - 重命名文件
    static func renameFile(path: AppDirectories, oldName: String, newName: String) -> Bool {
        let oldPath = FilePathUtils.setupFilePath(directory: path, name: oldName)
        let newPath = FilePathUtils.setupFilePath(directory: path, name: newName)
        do {
            try FileManager.default.moveItem(atPath: oldPath, toPath: newPath)
            return true
        } catch {
            return false
        }
    }

    // MARK: - 移動(dòng)文件
    static func moveFile(fileName: String, fromDirectory: String, toDirectory: String) -> Bool {
        let originPath = FilePathUtils.setupFilePath(directory: .customPath(path: fromDirectory), name: fileName)
        let destinationPath = FilePathUtils.setupFilePath(directory: .customPath(path: toDirectory), name: fileName)
        do {
            try FileManager.default.moveItem(atPath: originPath, toPath: destinationPath)
            return true
        } catch {
            return false
        }
    }

    // MARK: - 拷貝文件
    static func copyFile(fileName: String, fromDirectory: String, toDirectory: String) throws {
        let originPath = FilePathUtils.setupFilePath(directory: .customPath(path: fromDirectory), name: fileName)
        let destinationPath = FilePathUtils.setupFilePath(directory: .customPath(path: toDirectory), name: fileName)
        return try FileManager.default.copyItem(atPath: originPath, toPath: destinationPath)
    }

    // MARK: - 文件是否可寫
    static func isWritable(filePath: String) -> Bool {
        if FileManager.default.isWritableFile(atPath: filePath) {
            return true
        } else {
            return false
        }
    }

    // MARK: - 文件是否可讀
    static func isReadable(filePath: String) -> Bool {
        if FileManager.default.isReadableFile(atPath: filePath) {
            return true
        } else {
            return false
        }
    }

    // MARK: - 文件是否存在
    static func exists(filePath: String) -> Bool {
        if FileManager.default.fileExists(atPath: filePath) {
            return true
        } else {
            return false
        }
    }

    // MARK: - 獲取文件列表
    static func getFilePathList(folderPath: String) -> [String] {
        let fileManager = FileManager.default
        let fileList = try? fileManager.contentsOfDirectory(atPath: folderPath)
        return fileList ?? []
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市抽高,隨后出現(xiàn)的幾起案子判耕,更是在濱河造成了極大的恐慌,老刑警劉巖翘骂,帶你破解...
    沈念sama閱讀 218,386評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件壁熄,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡碳竟,警方通過(guò)查閱死者的電腦和手機(jī)草丧,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,142評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)莹桅,“玉大人昌执,你說(shuō)我怎么就攤上這事≌┢茫” “怎么了懂拾?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,704評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)铐达。 經(jīng)常有香客問(wèn)我岖赋,道長(zhǎng),這世上最難降的妖魔是什么瓮孙? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,702評(píng)論 1 294
  • 正文 為了忘掉前任贾节,我火速辦了婚禮,結(jié)果婚禮上衷畦,老公的妹妹穿的比我還像新娘栗涂。我一直安慰自己,他們只是感情好祈争,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,716評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布斤程。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪忿墅。 梳的紋絲不亂的頭發(fā)上扁藕,一...
    開(kāi)封第一講書(shū)人閱讀 51,573評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音疚脐,去河邊找鬼亿柑。 笑死,一個(gè)胖子當(dāng)著我的面吹牛棍弄,可吹牛的內(nèi)容都是我干的望薄。 我是一名探鬼主播,決...
    沈念sama閱讀 40,314評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼呼畸,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼痕支!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起蛮原,我...
    開(kāi)封第一講書(shū)人閱讀 39,230評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤卧须,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后儒陨,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體花嘶,經(jīng)...
    沈念sama閱讀 45,680評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,873評(píng)論 3 336
  • 正文 我和宋清朗相戀三年蹦漠,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了椭员。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,991評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡津辩,死狀恐怖拆撼,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情喘沿,我是刑警寧澤闸度,帶...
    沈念sama閱讀 35,706評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站蚜印,受9級(jí)特大地震影響莺禁,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜窄赋,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,329評(píng)論 3 330
  • 文/蒙蒙 一哟冬、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧忆绰,春花似錦浩峡、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,910評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春纸淮,著一層夾襖步出監(jiān)牢的瞬間平斩,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,038評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工咽块, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留绘面,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,158評(píng)論 3 370
  • 正文 我出身青樓侈沪,卻偏偏與公主長(zhǎng)得像揭璃,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子峭竣,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,941評(píng)論 2 355

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