swift 文件管理

4,175 阅读1分钟

刚刚写完公司项目,发现网上swift NSFileManager文件管理的文章都是swift5之前的语法。鉴于swift5已经趋于稳定,下面分享一下增删改查的代码。

一、如果不存在文件夹,则创建新的文件夹。并返回bool值

func createFolderIfNotExisits(folderPath : String)->Bool {

//获取沙盒路径

let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString

let fileManager = FileManager.default let filePath = documentPath as String + "/" + folderPath

let exist = fileManager.fileExists(atPath: filePath)

if !exist {

     try! fileManager.createDirectory(atPath: filePath,withIntermediateDirectories: true, attributes: nil)

}

return exist

}

二、获取指定路径下所有文件名

遍历方法有很多种,这只是其中一种

func getAllFileName(folderPath: String)->[String]{

let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString

let manager = FileManager.default let fileUrl = documentPath as String + "/" + folderPath

let subPaths = manager.subpaths(atPath: fileUrl)

let array = subPaths?.filter({$0 != ".DS_Store"})

return array!

}

三、删除文件

//删除置指定路径的文件,并返回Bool值。

func deleteFile(folderPath: String, fileName: String)->Bool{

var success = false let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString

let manager = FileManager.default

let fileUrl = documentPath as String + "/" + folderPath

let subPaths = manager.subpaths(atPath: fileUrl)

let removePath = fileUrl + "/" + fileName

for fileStr in subPaths!{

      if fileName == fileStr {

          try! manager.removeItem(atPath: removePath)

          success = true

          }

  }

        return success

}

四、写入文件

//传入指定路径,文件名。

func openICloudDrive(folderUrl : String,folderName : String{

let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString

let manager = FileManager.default

let fileManager = FileManager.default

let filePath = documentPath as String + "/" + self.folderUrl!

let exist = fileManager.fileExists(atPath: filePath)

if !exist {

try! fileManager.createDirectory(atPath: filePath,withIntermediateDirectories: true, attributes: nil)

}

let createFilePath = filePath + "/" + self.folderName!

if manager.fileExists(atPath: createFilePath) {

print("该路径下已经存在同名文件,文件创建失败")

} else {

let urlStr = url.absoluteString

let data = urlStr.data(using: String.Encoding.utf8)

let isSuccess = manager.createFile(atPath: createFilePath, contents: data!, attributes: nil)

print(isSuccess ? "文件创建成功" : "文件创建失败")

}

以上就是在swift5语法下的文件管理几种常见的操作。之后会陆续更新swift,感兴趣的可以点关注了~