IOS_swift文件系统

    func files(){
        //应用根目录
        let dir = NSHomeDirectory();
        NSLog("dir = \(dir)")
        
        // 文档目录
        let doc = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
        NSLog("doc = \(doc)")
        
        // library目录
        let library = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0]
        NSLog("doc = \(library)")
        
        //判断目录是否存在
        let manager = NSFileManager.defaultManager()
        let myDir = "\(doc)/my"
        let isExist = manager.fileExistsAtPath(myDir)
        if(isExist){
            NSLog("存在my文件夹")
        }else{
            NSLog("不存在my文件夹!")
            //创建文件夹
            do{
                try manager.createDirectoryAtPath(myDir, withIntermediateDirectories: true, attributes: nil)
            }catch{
            }
        }
        
        //判断文件是否存在
        let myTxt = "\(doc)/my.txt"
        let isExistMyTxt = manager.fileExistsAtPath(myTxt)
        if(isExistMyTxt){
            NSLog("存在my.txt")
        }else{
            NSLog("不存在my.txt")
            //创建文件
            manager.createFileAtPath(myTxt, contents: nil, attributes: nil)
        }
        
        // 用户首选项
        let userDefault = NSUserDefaults.standardUserDefaults()
        userDefault.setObject("2012", forKey: "time")
        userDefault.synchronize()
        
        let time = userDefault.stringForKey("time")
        NSLog("time = \(time!)")
        
        //保存文件
        let arr:NSArray = ["11","33","22"]
        arr.writeToFile(myTxt, atomically: true)
        
        let content = NSArray(contentsOfFile: myTxt)!
        print(content)
        
        //对象保存
        let stuPlist = "\(doc)/stu.plist"
        let stu = Student(name: "zhangsan", age: 20)
        NSKeyedArchiver.archiveRootObject(stu, toFile: stuPlist)
        
        let stu2 = NSKeyedUnarchiver.unarchiveObjectWithFile(stuPlist) as? Student
        if stu2 != nil {
            print("name = \(stu2!.name), age = \(stu2!.age)")
        }
    }

你可能感兴趣的:(ios,swift,文件系统,应用)