文件,文件夹操作

获取用户文档目录路径

        let manager = FileManager.default
        let urlForDocument = manager.urls(for: .documentDirectory, in:.userDomainMask)
        let url = urlForDocument[0] as URL
        print(url)

对指定路径执行浅搜索,返回指定目录路径下的文件、子目录及符号链接的列表

        let contentsOfPath = try? manager.contentsOfDirectory(atPath: url.path)
        print("contentsOfPath: \(contentsOfPath)")

类似上面的,对指定路径执行浅搜索,返回指定目录路径下的文件、子目录及符号链接的列表

        let contentsOfURL = try? manager.contentsOfDirectory(at: url,
                                                             includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
        print("contentsOfURL: \(contentsOfURL)")

深度遍历,会递归遍历子文件夹(但不会递归符号链接)

        let enumeratorAtPath = manager.enumerator(atPath: url.path)
        print("enumeratorAtPath: \(enumeratorAtPath?.allObjects)")

类似上面的,深度遍历,会递归遍历子文件夹(但不会递归符号链接)

        let enumeratorAtURL = manager.enumerator(at: url, includingPropertiesForKeys: nil,
                                                 options: .skipsHiddenFiles, errorHandler:nil)
        print("enumeratorAtURL: \(enumeratorAtURL?.allObjects)")

深度遍历,会递归遍历子文件夹(包括符号链接,所以要求性能的话用enumeratorAtPath)

        let subPaths = manager.subpaths(atPath: url.path)
        print("subPaths: \(subPaths)")

判断文件或文件夹是否存在

 let fileManager = FileManager.default
        let filePath:String = NSHomeDirectory() + "/Documents/aa.rtf"
        let exist = fileManager.fileExists(atPath: filePath)
        print("exist==============================\(exist)")
        //exist==============================true

创建文件夹

        let myDirectory:String = NSHomeDirectory() + "/Documents/myFolder/Files"
        //let fileManager = FileManager.default
        
        //withIntermediateDirectories为ture表示路径中间如果有不存在的文件夹都会创建
        try! fileManager.createDirectory(atPath: myDirectory,
                                         withIntermediateDirectories: true, attributes: nil)

将对象写入文件

     可以通过write(to:)方法,可以创建文件并将对象写入,对象包括String,NSString,UIImage,NSArray,NSDictionary等。
//String
        let filePath1:String = NSHomeDirectory() + "/Documents/GPL.txt"
        let info = "www.GPL.com"
        try! info.write(toFile: filePath1, atomically: true, encoding: String.Encoding.utf8)
        
        //图片
        //swift字符串+加号拼接
        let filePath2:String = NSHomeDirectory() + "/Documents/GPL.png"
        let image = UIImage(named: "GPLImage")
        let data:Data = UIImagePNGRepresentation(image!)!
        try? data.write(to: URL(fileURLWithPath: filePath2))
        
        //把NSArray保存到文件路径下
        let array = NSArray(objects: "aaa","bbb","ccc")
        let filePath3:String = NSHomeDirectory() + "/Documents/array.plist"
        array.write(toFile: filePath3, atomically: true)
        
        //把NSDictionary保存到文件路径下
        let dictionary:NSDictionary = ["Gold": "1st Place", "Silver": "2nd Place"]
        let filePath4:String = NSHomeDirectory() + "/Documents/dictionary.plist"
        dictionary.write(toFile: filePath4, atomically: true)

创建文件

func createFile(name:String, fileBaseUrl:URL){
let manager = FileManager.default

        let file = fileBaseUrl.appendingPathComponent(name)
        print("文件: \(file)")
        let exist = manager.fileExists(atPath: file.path)
        if !exist {
            let data = Data(base64Encoded:"aGVsbG8gd29ybGQ=" ,options:.ignoreUnknownCharacters)
            let createSuccess = manager.createFile(atPath: file.path,contents:data,attributes:nil)
            print("文件创建结果: \(createSuccess)")
        }
    }
    
    //在文档目录下新建test.txt文件
    let manager2 = FileManager.default
    let urlForDocument2 = manager2.urls( for: .documentDirectory,
                                       in:.userDomainMask)
    let aurl = urlForDocument2[0]
    createFile(name:"test.txt", fileBaseUrl: aurl)
    //createFile(name: "folder/new.txt", fileBaseUrl: url)
#复制文件
    let fileManager3 = FileManager.default
    let homeDirectory = NSHomeDirectory()
    let srcUrl = homeDirectory + "/Documents/GPL.txt"
    let toUrl = homeDirectory + "/Documents/copyed.txt"
    try! fileManager3.copyItem(atPath: srcUrl, toPath: toUrl)
# 移动文件
    let fileManager4 = FileManager.default
    let homeDirectory4 = NSHomeDirectory()
    let srcUrl4 = homeDirectory4 + "/Documents/GPL.txt"
    let toUrl4 = homeDirectory4 + "/Documents/moved/hangge.txt"
    try! fileManager4.moveItem(atPath: srcUrl4, toPath: toUrl4)
# 删除目录下所有的文件
    let fileManager6 = FileManager.default
    let myDirectory6 = NSHomeDirectory() + "/Documents/Files"
    let fileArray = fileManager6.subpaths(atPath: myDirectory)
    for fn in fileArray!{
        try! fileManager.removeItem(atPath: myDirectory6 + "/\(fn)")
    }

你可能感兴趣的:(文件,文件夹操作)