68- Swift 之文件管理(FileManager)

前言

在App的开发中,对文件的管理也是一项艰巨的工作。如果不谨慎的处理会造成很严重的结果。

一 、文件的一系列方法的介绍

1、 获取 Documentation 目录路径

/**
 获取 Domains 的路径
 1、 SearchPathDirectory 搜索目录的可选参数
 applicationDirectory : 在 applications 目录下搜索。
 demoApplicationDirectory : 在 applications/Demo 的目录下搜索。
 developerApplicationDirectory : 在 Developer/Applications 目录下搜索。
 adminApplicationDirectory : 在 Applications/Utilities 目录下搜索。
 libraryDirectory :在 Library 目录下搜索。
 developerDirectory : 在 Developer 目录下搜索,不只是一个开发者。
 userDirectory : 在用户的主目录下搜索。
 documentationDirectory : 在 Documentation 目录下搜索。
 documentDirectory : 在 Documents 目录下搜索。
 coreServiceDirectory : 在 System/Library/CoreServices 目录下搜索。
 autosavedInformationDirectory : 自动保存的文档位置搜索 (Documents/Autosaved)
 desktopDirectory : 在用户桌面搜索。
 cachesDirectory : 在本地缓冲目录在搜索(Library/Caches)
 applicationSupportDirectory :本地应用所支持的目录下搜索(Library/Application Support)。
 downloadsDirectory : 本地下载downloads目录。
 inputMethodsDirectory :在输入方法目录下搜索(Library/Input Methods)。
 moviesDirectory : 在用户电影目录搜索(~/Movies)。
 musicDirectory : 在用户音乐目录搜索(~/Music)。
 picturesDirectory: 在用户图片目录搜索(~/Pictures)。
 printerDescriptionDirectory : 在系统本地PPDs目录下搜索(Library/Printers/PPDs)。
 sharedPublicDirectory : 在本地用户分享目录下搜索(~/Public)。
 preferencePanesDirectory : 在系统的偏好设置目录在搜索(Library/PreferencePanes)。
 itemReplacementDirectory : For use with NSFileManager's URLForDirectory:inDomain:appropriateForURL:create:error:
 allApplicationsDirectory :应用能够发生的所有路径 。
 allLibrariesDirectory : 资源可以发生的所有目录 。
 2、 SearchPathDomainMask 路径领域的模糊搜索的可选参数
 userDomainMask :   用户的主目录路径领域搜索。
 localDomainMask :  当前设备本地路径领域搜索。
 networkDomainMask :网络共享的路径领域搜索。
 systemDomainMask : 由苹果提供的系统路径领域搜索。
 allDomainsMask :   上述所有情况的路径领域搜索。
 */

// TODO: 获取 Documentation 目录路径
let domainsArray = NwFileManager.urls(for:.documentDirectory, in: .userDomainMask)
let domainsPath = domainsArray[0] as URL
print(domainsPath)

或者

NSHomeDirectory() +  "/Documents"

2、 获取路径下的文件名字

let homePath = NSHomeDirectory()
// TODO: 获取路径下的文件名字
let contentsOfPath = try? NwFileManager.contentsOfDirectory(atPath: homePath + "/Documents")
print(contentsOfPath as Any)
/**
 输出结果: Optional([".DS_Store", "test", "text1.rtf"])
 */

3、 获取指定路径下的所有文件的路径URL

// TODO: 获取指定路径下的所有文件的路径URL
let contentsOfUrl = try? NwFileManager.contentsOfDirectory(at: URL.init(string: homePath + "/Documents")!, includingPropertiesForKeys: [URLResourceKey.creationDateKey], options: .skipsSubdirectoryDescendants)
print(contentsOfUrl as Any)

4、 深度遍历指定路径下的所有文件

// TODO: 深度遍历指定路径下的所有文件
var  allFiel = NwFileManager.enumerator(atPath: homePath + "/Documents")
print(allFiel?.allObjects as Any)
/**
 输出结果:Optional([.DS_Store, test, test/DSC_0162.jpg, text1.rtf])
 */

或者

// 另一种深度遍历文件的方法
let subPath = NwFileManager.subpaths(atPath: homePath + "/Documents")
print(subPath as Any)
/**
 输出的结果:
 Optional([".DS_Store", "test", "test/DSC_0162.jpg", "text1.rtf"])
 */

5、 把指定文件的转换成 Data 二进制流数据

// TODO: 把指定文件的转换成 Data 二进制流数据
let NwData = NwFileManager.contents(atPath: homePath + "/Documents/text1.rtf")
print(NwData!)
/**
 输出结果:Optional("417 bytes")
 */

6、 创建文件

// TODO: 创建文件
var isFile = NwFileManager.createFile(atPath: homePath + "/Documents/MyFile", contents: nil, attributes: nil)
print(isFile)
/**
 输出结果: true 表示创建成功 ; false 表示创建失败
 */

let data = Data.init(base64Encoded: "我是中国人!")
isFile = NwFileManager.createFile(atPath: homePath + "/Documents/MyFile.txt", contents: data, attributes: nil)
print(isFile)
/**
 输出结果: true 表示创建成功 ; false 表示创建失败
 */

7、判断文件是否存在

// TODO: 判断文件是否存在
var isSave = NwFileManager.fileExists(atPath: homePath + "/Documents/MyFile.txt")
print(isSave)
var directory: ObjCBool = ObjCBool(true)
isSave = NwFileManager.fileExists(atPath: homePath + "/Documents/MyFile.txt", isDirectory: &directory)
print(isSave)
/**
 输出结果: true 表示存在 ; false 表示不存在
 */

8、判断文件的权限

// TODO: 判断文件是否可读
let isRead = NwFileManager.isReadableFile(atPath: homePath + "/Documents/MyFile.txt")
print(isRead)

// TODO: 判断文件是否可写
let isWrite = NwFileManager.isWritableFile(atPath: homePath + "/Documents/MyFile.txt")
print(isWrite)

// TODO: 判断文件是否是可执行文件
let isExecutable = NwFileManager.isExecutableFile(atPath: homePath + "/Documents/MyFile.txt")
print(isExecutable)

// TODO: 判断文件是否可以删除
let isDele = NwFileManager.isDeletableFile(atPath: homePath + "/Documents/MyFile.txt")
print(isDele)

9、获取文件的本地名字和文件所有路径的名字集合

// TODO: 返回文件的本地显示名字
let disName = NwFileManager.displayName(atPath: homePath + "/Documents/MyFile.txt")
print(disName)

// TODO: 获取路径下的所有文件的名字
let componentsDisName = NwFileManager.componentsToDisplay(forPath: homePath + "/Documents")
print(componentsDisName as Any)
/**
 输出结果:
 Optional(["/", "Users", "mac", "Library", "Developer", "CoreSimulator", "Devices", "4B05A965-A582-4E49-933F-145481D7F06A", "data", "Containers", "Data", "Application", "D5BAF1B3-B3A7-43B7-B45B-135F1682DE09", "Documents"])
 */

10 、 数据的写入和保存

// MARK: 文件数据的写入
let info = "我是中国人,我爱我的国家!"
try! info.write(toFile: homePath + "/Documents/MyFile.txt", atomically: true, encoding: .utf8)

// MARK: 将数组保存
let arraySave = NSArray.init(arrayLiteral: "a","b","c")
arraySave.write(toFile: homePath + "/Documents/MyFilePlist.plist", atomically: true)

// MARK: 将字典保存
let dictionSave = NSDictionary.init(dictionaryLiteral: ("A","ccc"),("B","bb"),("C","bbx"))
dictionSave.write(toFile: homePath + "/Documents/MyFilePlist.plist", atomically: true)

// MARK: 将Data 保存
let imagData = UIImagePNGRepresentation(UIImage.init(named: "colors.jpg")!)
try? imagData?.write(to: URL.init(fileURLWithPath: homePath + "/Documents/MyPicture.jpg"))

11 、文件的复制、移动、删除、读取 操作

// MARK: 文件的复制(注意:将要复制出的文件,如果存在。将复制失败)
let startFilePath = homePath + "/Documents/MyFile.txt"
let toFilePath = homePath + "/Documents/MyFileCopy.txt"
try! NwFileManager.copyItem(at:URL.init(fileURLWithPath: startFilePath) , to: URL.init(fileURLWithPath: toFilePath))

// MARK: 文件的移动
let MoveStartFilePath = homePath + "/Documents/MyFileCopy.txt"
let MoveToFilePath = homePath + "/Documents/test/MyFileCopy.txt"
try! NwFileManager.moveItem(atPath: MoveStartFilePath, toPath: MoveToFilePath)

// MARK: 删除文件
let DeleFilePath  = homePath + "/Documents/test/MyFileCopy.txt"
try! NwFileManager.removeItem(atPath: DeleFilePath)

// MARK: 数据的读取
let readDataPath = homePath + "/Documents/MyFile.txt"
let dataInfo = NwFileManager.contents(atPath: readDataPath)
let readStr = String.init(data: dataInfo!, encoding: .utf8)
print(readStr!)

12 、 获取文件的属性和基本一些文件信息

// MARK: 获取文件的属性
let attributes = try! NwFileManager.attributesOfFileSystem(forPath: homePath + "/Documents/MyFile.txt")
print(attributes)
/**
 输出结果
 [__C.FileAttributeKey(_rawValue: NSFileSystemFreeSize): 808617267200, __C.FileAttributeKey(_rawValue: NSFileSystemNumber): 16777218, __C.FileAttributeKey(_rawValue: NSFileSystemSize): 999345127424, __C.FileAttributeKey(_rawValue: NSFileSystemNodes): 4294967279, __C.FileAttributeKey(_rawValue: NSFileSystemFreeNodes): 4292611890]
 */
// 获取一些文件的基本信息
let CreateData = attributes[FileAttributeKey.creationDate]
let FileSzie =  attributes[FileAttributeKey.systemSize]
print(CreateData as Any)
print(FileSzie as Any)

13、当前域的路径获取和文件路径的变更

// MARK: 获取文件的当前路径
let CurrentPath = NwFileManager.currentDirectoryPath
print(CurrentPath)

// MARK: 文件路径的变更
let exchangePath = "desktop"
let  isExchangePath = NwFileManager.changeCurrentDirectoryPath(exchangePath)
print(isExchangePath)

14 、 文件或者文件夹的比较

// MARK: 文件的比较
let  oneFilePath = homePath + "/Documents/MyFile.txt"
let  otherFilePath = homePath + "/Documents/MyFilePlist.plist"
let isEqual = NwFileManager.contentsEqual(atPath: oneFilePath, andPath: otherFilePath)
print(isEqual)

// 文件夹的比较
let FilePath = homePath + "/Documents/test"
let FilePathOne = homePath + "/Documents/test1"
let isEqualFile = NwFileManager.contentsEqual(atPath: FilePath, andPath: FilePathOne)
print(isEqualFile)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,568评论 25 707
  • linux资料总章2.1 1.0写的不好抱歉 但是2.0已经改了很多 但是错误还是无法避免 以后资料会慢慢更新 大...
    数据革命阅读 12,016评论 2 34
  • 但凡是人,都会攀比,商人比财力、政客比权利、学生比成绩、父母比子女、销售人员比业绩、......当然,攀比不见得是...
    汀然Amily阅读 719评论 0 1
  • 他们所居住的地方主要有三个,一个是在敬老院集体安养,敬老院是由政府出钱修建的,里面的健身设备全部由政府和村委买单。...
    臆想与脑洞阅读 168评论 0 0