swift中的文件操作

自从学习了iOS的新语言就感觉一个更加有趣的世界开启了,它的横空出世必定会带来一番腥风血雨。这次就谈谈Swift中关于文件的操作,记忆中学习Swift差不多一个月就可以上手些项目了,比较深的体会是它面向对象的语言特征更加刻骨。有OC基础的童靴学习Swift是不在话下的,不过它还是有很多强大的东西是你必须花时间去掌握的。这次带来自己封装的一个文件操作的类引擎:

关于文件判无和路径的实例方法:


//   在Document路径下判断,什么这里返回值是可选的字符串值呢,这里可选是因为返回值可能为nil,其他返回值为可选类型的同样是这个规则。
    func localDocumentsPath(fileName:String) ->String?{
        return createNeeded(fileName)
    }
    
    //    文件不存在则创建为
    func createNeeded(fileName:String) ->String?{
        let fileManage = NSFileManager.defaultManager()
        let filePath = returnDocumentsPathWithFileName(fileName)
        if !fileManage.fileExistsAtPath(filePath!){
            let bundlePath = NSBundle.mainBundle().resourcePath
            let defaultFilePath = bundlePath! + "/\(NoteFile)"
            do{
                try fileManage.copyItemAtPath(defaultFilePath, toPath: filePath!)
            }catch{
                print("错误写入文件!")
            }
        }
        
        return filePath
    }
    //  文件Document路径
    func returnDocumentsPathWithFileName(fileName:String) ->String?{
        let documentDir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last
        let documentPath = "\(documentDir!)/\(fileName)"
        return documentPath

两个静态方法分别进行文件的读和写,写的时候在静态方法中调用实例方法会发现调不了,什么鬼。。。 然后你会思考怎么调,其实在静态方法里可以用很多方式来调用实例方法,这里给出一种方式:

    class func readCurrentFile(fileName:String) -> String?{
        let currentClassObject = FileManagerEngine()
        let filePath = currentClassObject.localDocumentsPath(localDataFile)
        let fileManage = NSFileManager.defaultManager()
        var content: String?
        if fileManage.fileExistsAtPath(filePath!){
            let tmpData = NSData.init(contentsOfFile: filePath!)
            content = String.init(data: tmpData!, encoding: NSUTF8StringEncoding)
        }
        return content
    }
    
    
    class func writeNoteToFileWithData(stringData:String) {
        let currentClassObject = FileManagerEngine()
       let filePath = currentClassObject.localDocumentsPath(localDataFile)
        let writeData = NSMutableData.init(contentsOfFile: filePath!)
        writeData!.appendData(stringData.dataUsingEncoding(NSUTF8StringEncoding)!)
        writeData!.writeToFile(filePath!, atomically: true)
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值