本文主要是介绍ios文件操作之目录操作-NSFileManager,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
//
// ViewController.swift
// NSFileManager_Test
//
// Created by power on 16/6/1.
// Copyright © 2016年 power. All rights reserved.
//import UIKitclass ViewController: UIViewController
{//延迟加载,每次调用时,返回NSSearchPathForDirectoriesInDomains数组的第一个值,也就是目录位置lazy var documentsPath:String = {let paths =NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask,true)return paths.first!}()overridefunc viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading the view, typically from a nib.directoryTest() //目录测试函数fileTest() //文件测试函数}func directoryTest(){let path ="\(documentsPath)/Data"print(path)if !directoryExistsAtPath(path){createDirectoryAtPath(path)}
// deleteDirectoryAtPath(path)
// directoryExistsAtPath(path)}//判断目录是否存在,返回布尔值func directoryExistsAtPath(path:String) ->Bool {let fileManager =NSFileManager.defaultManager()let result = fileManager.fileExistsAtPath(path)//系统判断目录或者文件是否存在,都用的是fileExistsAtPath()方法if result{print("dirctory exists...")}else{print("dirctory not exists...")}return result}//创建目录,参数为穿件目录func createDirectoryAtPath(path:String){let fileManager =NSFileManager.defaultManager()do{try fileManager.createDirectoryAtPath(path, withIntermediateDirectories:false, attributes: nil)}catch //如果创建失败,则打印一行报告{print("create directory failed")}}//删除目录方法,参数为传入路径func deleteDirectoryAtPath(path:String){let fileManager =NSFileManager.defaultManager()do{try fileManager.removeItemAtPath(path)}catch{print("delete directory failed")}}func fileTest(){let path ="\(documentsPath)/data.txt"print(path)if !fileExistsAtPath(path){createFileAtPath(path)fileExistsAtPath(path)}}func fileExistsAtPath(path:String) ->Bool{let fileManager =NSFileManager.defaultManager()let result = fileManager.fileExistsAtPath(path)if result{print("file exists")}else{print("file net exists")}return result}func createFileAtPath(path:String){let fileManager =NSFileManager.defaultManager()fileManager.createFileAtPath(path, contents:nil, attributes: nil)}func deleteFileAtPath(path:String){let fileManager =NSFileManager.defaultManager()do{try fileManager.removeItemAtPath(path)}catch{print("delete File failed")}}overridefunc didReceiveMemoryWarning() {super.didReceiveMemoryWarning()// Dispose of any resources that can be recreated.}}
这篇关于ios文件操作之目录操作-NSFileManager的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!