【Swift】文件、文件夹操作

定位到用户文档目录

  let manager = FileManager.default
  let url = manager.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first as NSURL!

创建文件

 func createFile(name:String, baseUrl:NSURL){
        let manager = FileManager.default
        let fileUrlPath = baseUrl.appendingPathComponent(name)
        
        let exist = manager.fileExists(atPath: (fileUrlPath?.path)!)
        if !exist {
            manager.createFile(atPath:(fileUrlPath?.path)!, contents: nil, attributes: nil)
        }
    }

创建文件夹

// 创建文件夹
    func createFolder(name:String, baseUrl:NSURL) {
        let manager = FileManager.default
        let folderUrlPath = baseUrl.appendingPathComponent(name)
        
        let exist = manager.fileExists(atPath: (folderUrlPath?.path)!)
        if !exist { // 判断是否已存在此文件夹,若不存在则创建文件夹
            // withIntermediateDirectories为ture表示路径中间如果有不存在的文件夹都会创建
            try? manager.createDirectory(at: folderUrlPath!, withIntermediateDirectories: true, attributes: nil)
        }
    }

使用方法

(1)创建文件
self.createFile(name: "test.txt", baseUrl: url as NSURL!)
(2)创建文件夹
self.createFolder(name: "folder", baseUrl: url as NSURL!)

运行结果

【Swift】文件、文件夹操作_第1张图片
807DF492-7640-4133-A40E-567A685D3408.png

你可能感兴趣的:(【Swift】文件、文件夹操作)