美文网首页
IOS文件管理

IOS文件管理

作者: Jackjun | 来源:发表于2016-09-05 20:29 被阅读0次

    文件操作

    NSFileManager

    1.NSFileManager 专门负责文件/文件夹的管理操作,包括创建/删除/移动/拷贝

    2.NSFileManager 是一个单例类

    3.NSFileManager 中所有的功能是通过变量型方法提供的

    声明一个文件操作的路径

    let path = "/Users/qianfeng/Desktop/iOS学习/swift语言阶段/第四周/day5-/实验文件夹"

    1.获取单例对象

    let fileManager = NSFileManager.defaultManager()

    2.浅度遍历

    函数原型:public func contentsOfDirectoryAtPath(path: String) throws -> [String]

    参数:需要遍历文件夹的路径

    功能:获取指定路径文件夹下的所有文件或文件夹的相对路径(相对于指定文件夹来说)->获取指定文件夹下所有文件或文件夹的名字;不能获取当前目录下子目录中的内容

    try? 如果后面有异常那么函数返回值是nil;如果没有异常返回值就是函数返回值类型的值

    let contents = try? fileManager.contentsOfDirectoryAtPath(path)

    if let content2 = contents {

    print("浅度遍历结果:\(content2)")

    }else{

    print("有异常")

    }

    3.深度遍历

    函数原型: public func subpathsOfDirectoryAtPath(path: String) throws -> [String]

    参数:需要遍历文件夹路径

    功能:获取指定路径文件夹下的所有文件或文件夹的相对路径(相对于指定文件夹来说)->能获取当前目录下所有的子目录的内容

    try? 如果后面有异常那么函数返回值是nil;如果没有异常返回值就是函数返回值类型的值

    let subContents = try? fileManager.subpathsOfDirectoryAtPath(path)

    if subContents != nil {

    print("深度遍历结果:\(subContents!)")

    }else{

    print("有异常")

    }

    4.创建目录

    函数原型:public func createDirectoryAtPath(path: String, withIntermediateDirectories createIntermediates: Bool, attributes: [String : AnyObject]?) throws

    参数1:需要创建目录的路径(注意:这个目录必须是需要创建好的文件夹的目录)

    参数2:是否创建中间目录(如果传人true,会自动创建目录中不存在的所有的中间目录)

    参数3:nil(创建的文件夹是默认属性)

    do{ }catch{ } 异常处理函数

    do{

    try fileManager.createDirectoryAtPath(path+"/123/ddd", withIntermediateDirectories: true, attributes: nil)

    }catch{

    //如果获取到do中调用的函数异常,就会执行catch

    print("创建目录异常")

    }

    5.创建文件

    函数原型:public func createFileAtPath(path: String, contents data: NSData?, attributes attr: [String : AnyObject]?) -> Bool

    参数1:需要创建文件的路径(路径中必须拼接创建好的文件的名字)

    参数2:需要在创建时给文件中写入的数据(如果是nil就不写数据到文件中)

    参数3:文件属性(传nil是默认属性)

    返回值:是否创建成功

    功能:在指定位置创建一个文件,并且写入指定数据;如果文件已存在,创建的时候会覆盖原来的文件

    .txt 文件用来存储文本,文本对应程序中的字符串。这里写入的数据应该是字符串数据

    NSDate 二进制类型,在iOS或swift中所有和本地文件或者服务器进行数据交流,必须以二进制的形式进行数据传递

    let wirteStr = "胜利收发货了客户问人家了一个人加我我if交流环节收费hi还是该符号没我份呢林森浩"

    将字符串转换为NSDate

    参数:编码方法(NSUTF8StringEncoding是中文编码方式)

    let data1 = wirteStr.dataUsingEncoding(NSUTF8StringEncoding)

    let ret1 = fileManager.createFileAtPath(path+"/444.txt", contents: data1, attributes: nil)

    if ret1 {

    print("文件创建成功")

    }else{

    print("文件创建失败")

    }

    将图片文件/音频/视频文件转化为二进制文件

    将本地文件转化为二进制

    let vidio1 = NSData.init(contentsOfFile: "/Users/qianfeng/Desktop/iOS学习/swift语言阶段/第一周牛眼睛/第三天/html/2-Resource/MovieTest.mp4")

    let ret2 = fileManager.createFileAtPath(path+"/m.mp4", contents: vidio1, attributes: nil)

    if ret2 {

    print("文件创建成功")

    }else{

    print("文件创建失败")

    }

    6.删除文件/目录

    函数原型: public func removeItemAtPath(path: String) throws

    函数原型里面有"throws"就要加"try"

    参数:需要删除的文件或目录的地址

    do{

    try fileManager.removeItemAtPath(path+"/bbb")

    }catch{

    print("删除文件/目录异常")

    }

    7.判断文件或者目录是否存在

    函数原型;public func fileExistsAtPath(path: String) -> Bool

    参数:需要判断的文件/目录的路径

    返回值:判断结果

    let ret3 = fileManager.fileExistsAtPath(path)

    if ret3 == true {

    print("文件/目录存在")

    }else{

    print("文件/目录不存在")

    }

    8.判断文件或者目录是否存在,同时判断是否是目录

    函数原型:fileExistsAtPath(path: String, isDirectory: UnsafeMutablePointer) -> Bool

    参数1:需要判断的文件/目录的路径

    参数2:存储是否是目录的结果(需要传入一个objeCBool类型的指针,对应到swift中就是地址)

    返回值:是否存在的结果

    "&" 取地址的符号

    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.获取文件/目录的属性

    函数原型: public func attributesOfItemAtPath(path: String) throws -> [String : AnyObject]

    参数:获取文件/目录的路径

    let attributes = try? fileManager.attributesOfItemAtPath(path)

    if attributes != nil {

    print("属性:\(attributes!)")

    print(attributes!["NSFileCreationDate"]!)

    }else{

    print("获取属性异常")

    }

    10.文件/目录的拷贝

    函数原型:public func copyItemAtPath(srcPath: String, toPath dstPath: String) throws

    参数1:源文件/目录路径

    参数2:目的路径(需要拼接拷贝成功后的文件名/目录名)

    do{

    try fileManager.copyItemAtPath(path+"/444.txt", toPath: path+"/123/444.txt")

    }catch{

    print("拷贝异常")

    }

    11.文件/目录的移动

    函数原型:public func moveItemAtPath(srcPath: String, toPath dstPath: String) throws

    参数1:源文件/目录路径

    参数2:目的路径(需要拼接移动成功后的文件名/目录名)

    do{

    try fileManager.moveItemAtPath(path+"/m.mp4", toPath: path+"/123/mm.mp4")

    }catch{

    print("移动异常")

    }

    文件读写

    NSFileHandle (文件代言人)

    将文件和NSFileHandle对象关联在一起后,对NSFileHandle对象进行操作相当于对文件本身进行操作

    let path = "/Users/qianfeng/Desktop/iOS学习/swift语言阶段/第四周/day5-/实验文件夹/444.txt"

    1.创建方式:

    a.以读的形式打开一个文件来创建这个文件对应的NSFileHandle对象;只能通过NSFileHandle对象对文件进行读操作

    参数:与NSFileHandle对象关联的文件路径

    let handle0 = NSFileHandle.init(forReadingAtPath: path)

    var handle: NSFileHandle = NSFileHandle()

    if let thandle = handle0{

    handle = thandle

    }else{

    print("关联失败")

    }

    2.读取指定长度的文件内容

    函数原型:public func readDataOfLength(length: Int) -> NSData

    参数:长度(单位:字节)

    let data2 = handle.readDataOfLength(200)

    //将NSData转换成字符串

    let str2 = String.init(data: data2, encoding: NSUTF8StringEncoding)

    print("指定长度\n:\(str2!)")

    总结:使用同一个文件句柄对象去多次读取文件操作,每次读取都是从上一次读取到的位置接着往后读取

    3.读取到文件尾

    函数原型:public func readDataToEndOfFile() -> NSData

    let data1 = handle.readDataToEndOfFile()

    print(data1)

    将NSData转换成字符串

    let str1 = String.init(data: data1, encoding: NSUTF8StringEncoding)

    print("读取到文件尾:\n\(str1!)")

    4.定位读写进度

    将读写进度定位到文件的最后

    handle.seekToEndOfFile()

    将读写进度定位到指定位置

    参数:距离文件开始位置的偏移大小(0 ->就是定位到文件开始位置)

    handle.seekToFileOffset(0)

    b.以写的形式去创建文件句柄(只能通过文件句柄对象进行写操作)

    let handleW = NSFileHandle.init(forWritingAtPath: path)

    var handle2 = NSFileHandle()

    if let thandle = handleW {

    handle2 = thandle

    }else{

    print("写关联失败")

    }

    1.将数据写入文件中

    函数原型:public func writeData(data: NSData)

    参数:需要写入文件中的数据

    功能:第一次写的时候从文件的开始位置写,会覆盖原来位置上的数据;多次进行写操作的时候,每次都是在上次写入结束的位置接着写

    如果想要从文件尾开始写数据,只需要在写之前将读写进度定位到文件尾

    handle2.seekToEndOfFile()    //默认定位到文件尾

    let str3 = "dfkikkkkkkkkkkkkkkkkkkkk"

    let data3 = str3.dataUsingEncoding(NSUTF8StringEncoding)

    handle2.writeData(data3!)

    let str4 = "aaaaaaaaaaaaaaaaaa"

    let data4 = str4.dataUsingEncoding(NSUTF8StringEncoding)

    handle2.writeData(data4!)

    2.清除文件内容

    参数:清除文件后剩余的内容的字节数。留的是文件前半部分内容,从后往前清理。(0 ->全部清空)

    handle2.truncateFileAtOffset(0)

    练习:

    调用函数方式整理文件

    let ret = GJFileManager.sortOutDirectory(path: "/Users/qianfeng/Desktop/iOS学习/swift语言阶段/第四周/day5-文件操作/zuoye/homekwork")

    class GJFileManager {

    //函数功能:整理文件夹

    //参数:需要整理的文件夹的路径

    //返回值:文件夹整理是否成功

    static func sortOutDirectory(path path: String) -> Bool {

    let fileManager = NSFileManager.defaultManager()

    //1.检查路径是否合法

    var isDirectory:ObjCBool = ObjCBool(false)

    //判断当前路径下的文件/文件夹是否存在,并且判断是否是目录

    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.浅度遍历文件夹,获取文件夹中所有内容

    let contents = try! fileManager.contentsOfDirectoryAtPath(path)

    print(contents)

    //2.遍历文件夹中的所有内容

    for fileName in contents {

    print(fileName)

    //判断是否是文件夹

    var isDirectory = ObjCBool(false)

    //拼接出文件/文件夹路径

    let filePath = path+"/"+fileName

    fileManager.fileExistsAtPath(filePath, isDirectory: &isDirectory)

    //如果是文件夹

    if isDirectory {

    //创建文件夹DIR

    do{

    try fileManager.createDirectoryAtPath(path+"/DIR", withIntermediateDirectories: true, attributes: nil)

    }catch{

    print("文件夹已经存在")

    }

    //将文件夹移动到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.将后缀转换为大写字母

    let upSuffix = suffix.uppercaseString

    //4.创建对应的文件夹

    do{

    try fileManager.createDirectoryAtPath(path+"/"+upSuffix, withIntermediateDirectories: true, attributes: nil)

    }catch{

    }

    //5.移动文件

    do{

    try fileManager.moveItemAtPath(filePath, toPath: path+"/"+upSuffix+"/"+fileName)

    }catch{

    }

    }

    }

    }

    }

    相关文章

      网友评论

          本文标题:IOS文件管理

          本文链接:https://www.haomeiwen.com/subject/xgbxsttx.html