沙盒文件读写

//  ViewController.swift

import UIKit
//默认生成的主控制器类
class ViewController: UIViewController {
    //当控制器的视图类夹在完成时调用
    override func viewDidLoad() {
        super.viewDidLoad()
        self.testSandBoxFileWriterOperation()//调用写文件方法
        self.testSandBoxFileReadOperation()//调用读文件方法
        // Do any additional setup after loading the view, typically from a nib.
    }
    //系统触发内存警告的时候调用
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    //写沙盒文件
    func testSandBoxFileWriterOperation()
    {
        //获取程序Home目录
        var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as Array<String>
        let documentPath:String? = paths[0]
        //判断是否获取成功
        if let _ = documentPath
        {
            //拼接实际文件路径
            let filePath = documentPath! + "/MagixBox.txt"
            //测试存储内容
            let content:NSArray = ["Hello,world","hahahahah","中文"]
            //写入文件,写入的内容是xml格式的
            let bRet = content.writeToFile(filePath, atomically: true)
            //打印写入结果
            if bRet == true
            {
                print("成功")
            }
            else
            {
                print("失败")
            }
        }
    }
    //读取沙盒文件内容
    func testSandBoxFileReadOperation()
    {
        //获得程序Home路径
        var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as Array<String>
        let documentPath:String? = paths[0]
        //判断是否获取成功
        if let _ = documentPath
        {
            //拼接文件路径
            let filePath = documentPath! + "/MagixBox.txt"
            //读取内容,这里的到的内容是一个可选类型
            let fileContent = NSArray(contentsOfFile: filePath)
            print(fileContent!)
        }

    }

}

标签: swift

添加新评论