美文网首页
简单读写操作

简单读写操作

作者: Grt婷 | 来源:发表于2017-07-29 14:46 被阅读0次

    一、NSString,data,NSArray,NSDictionary数据的读写

    1.NSString的读写

    //1.要写的文件夹
            let name="今天天气真好"
            var path=NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            path += "/name.text"
            print(path)
            let fileM=FileManager()
            //判断文件是否存在
            if !fileM.fileExists(atPath: path){
                   //2.创建文件
                    fileM.createFile(atPath: path, contents: nil, attributes: nil)
            }
            //3.写入
            let url=URL(fileURLWithPath: path)
             //try捕获异常/错误抛出
            try! name.write(to:url,atomically:true,encoding:.utf8)
            //4.读取
            let name1=try! String(contentsOfFile: path)
            print("name1="+name1)
           //单例 不会被释放可以存放值
            //UIApplication.shared.keyWindow
            //UserDefaults.standard
    
    

    2.data的读写

    //找一张图片放在document中
            let imagePath=Bundle.main.path(forResource: "1", ofType: "jpg")
            // 根据图片路径读取出二进制流(Data)
            let data = try! Data(contentsOf: URL(fileURLWithPath: imagePath!))
            var  imagePath1 = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            imagePath1 += "/1.jpg"
            print(imagePath1)
            // 创建文件  head.jpg
            if !fileM.fileExists(atPath: imagePath1) {
                fileM.createFile(atPath: imagePath1, contents: nil, attributes: nil)
            }
    
            //3.写入
            try! data.write(to: URL(fileURLWithPath: imagePath1))
            // 把图片读取出来
            let imgData = try! Data(contentsOf: URL(fileURLWithPath: imagePath1))
            // 根据data转换成图片
            let image = UIImage(data: imgData)
            let imageView = UIImageView(image: image)
            self.view.addSubview(imageView)
    

    3.NSArray的读写

     let nameArry=["小明","小李","小王"]
            var arrypath=NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            arrypath += "/arry.plist"
            print(arrypath)
            //判断文件是否存在
            if !fileM.fileExists(atPath: arrypath){
                //2.创建文件
                fileM.createFile(atPath: arrypath, contents: nil, attributes: nil)
            }
            //3.写入
            //写入到文件的路径
            let url1=URL(fileURLWithPath: arrypath)
            print(url1)
            //写入到文件
            (nameArry as NSArray).write(to: url1, atomically: true)
            //try捕获异常/错误抛出
            //4.读取
            let nameArray1=NSArray(contentsOfFile: arrypath)
            print(nameArray1)
    
    

    相关文章

      网友评论

          本文标题:简单读写操作

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