Swift文件管理必知的一些操作

96
叫我干苦力的码农
2016.06.12 15:39* 字数 872

前言:作为一个iOS开发人员,我们都了解沙盒机制,每个应用程序都有自己独立的储存空间(大名就是"沙盒"),沙盒是:应用程序只能对自己创建的文件系统读取文件,这个独立、封闭、安全的空间,它一般存放着程序包含的文件(即可执行文件)/图片/音频/视频/plish文件/sqlite数据库及其他文件.
然后让我们看一下沙盒的位置及目录文件

. 根目录获取方式

let home = NSHomeDirectory() as NSString;
print("沙盒根目录:\\(home)")

然后把通过文件查找(如图1所示:),我们就会发现根目录下面的文件夹,具体文件夹如下所述:

. 根目录下面的文件夹分别是Document / Library / temp

1). Document:一般需要持久的数据都放在此目录中,可以在当中添加子文件夹,iTunes备份和恢复的时候,会包括此目录:
Document获取方式

 let DocumentPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.AllDomainsMask, true)

2). temp:创建临时文件的目录,当iOS设备重启时,文件会被自动清除:
tempPath获取方式

let tempPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory,NSSearchPathDomainMask.AllDomainsMask, true)

3). Library:设置程序的默认设置和其他状态信息:
Library获取方式

let libraryPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.LibraryDirectory,NSSearchPathDomainMask.AllDomainsMask, true)

通过上面部分我们了解了沙盒的位置及根目录下面的一切东西,我们就来具体看看怎么对文件和文件夹的操作,操作它我们使用NSFileManager,NSFileHandle等类来实现, 具体操作我也总结以下几点

1. 创建文件夹
1).第一种方法:

 let myDire: String = NSHomeDirectory() + "/Documents/Rookie/Files"
    let fileManager = NSFileManager.defaultManager()
    try! fileManager.createDirectoryAtPath(myDire,
                                           withIntermediateDirectories: true, attributes: nil)

2).第二种方法:

// NSSearchPathDirectory.DocumentDirectory 查找Documents文件夹
// NSSearchPathDomainMask.UserDomainMask 在用户的应用程序下查找
    let manager2 = NSFileManager.defaultManager()
        let urlForDocument2 = manager2.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask)
        let url2 = urlForDocument2[0] as NSURL
        createFolder("RookieSon", baseUrl: url2)
 

    func createFolder(name:String,baseUrl:NSURL){
        let manager = NSFileManager.defaultManager()
        let RookieSon = baseUrl.URLByAppendingPathComponent(name, isDirectory: true)
        print("文件夹: \\(RookieSon)")
        let exist = manager.fileExistsAtPath(RookieSon.path!)
        if !exist {
            try! manager.createDirectoryAtURL(RookieSon,withIntermediateDirectories: true, attributes: nil)
        }
  • 第二种方法我们创建的文件格式是file:// 开头的

2. 了解一个具体目录下的所有文件
1).对指定路径执行浅搜索,返回指定目录路径下的文件、子目录及符号链接的列表

let contentsOfPath = try? manager.contentsOfDirectoryAtPath(url.path!)
    print("contentsOfPath: \\(contentsOfPath)")

输出结果:

contentsOfPath: Optional([".DS_Store", "arr.plist", "Rookie", "RookieSon", "RookieString.png", "RookieString.txt", "String.png", "test.txt"])

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

let contentsOfURL = try? manager.contentsOfDirectoryAtURL(url, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles)

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

let enumeratorAtPath = manager.enumeratorAtPath(url.path!)

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

let enumeratorAtURL = manager.enumeratorAtURL(url, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler:nil)

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

let subPaths = manager.subpathsAtPath(url.path!)

** 3. 判断文件或者我们的文件夹是否存在**
使用: public func fileExistsAtPath(path: String) -> Bool

let isFileManager = NSFileManager.defaultManager()
    let isFilePath:String = NSHomeDirectory() + "/Documents/RookieString.txt"
    let exist = isFileManager.fileExistsAtPath(isFilePath)
    print(exist)

4. 将对象写入指定文件中
使用:
public func writeToFile(path: String, atomically useAuxiliaryFile: Bool, encoding enc: NSStringEncoding) throws
public func writeToFile(path: String, atomically useAuxiliaryFile: Bool) -> Bool

1).将String保存到文件夹中
    let StringPath: String = NSHomeDirectory() + "/Documents/RookieString.txt"
            let stringInfo = "存储的String"
            try! stringInfo.writeToFile(StringPath, atomically: true, encoding: NSUTF8StringEncoding)
            print("String存储文件位置 : \\(StringPath)")
 2).将Image保存到文件中
let imagePath:String = NSHomeDirectory() + "/Documents/String.png"
        let image = UIImage(named: "1")
 3).将数组保存到文件中
     let imageData:NSData = UIImagePNGRepresentation(image!)!
        imageData.writeToFile(imagePath, atomically: true)
 4).将字典保存到文件中
     let arr = NSArray(objects:"Rookie","YX","fight")
        let arrayPath: String = NSHomeDirectory() + "/Documents/arr.plist"
        arr.writeToFile(arrayPath, atomically: true)

5. 创建文件
使用:

 public func URLsForDirectory(directory: NSSearchPathDirectory, inDomains domainMask: NSSearchPathDomainMask) -> [NSURL]

 //在文档目录下新建test.txt文件
    let testManager = NSFileManager.defaultManager()
    let testurlForDocument = testManager.URLsForDirectory( NSSearchPathDirectory.DocumentDirectory,
                                                           inDomains:NSSearchPathDomainMask.UserDomainMask)
    let testUrl = testurlForDocument[0] as NSURL
    createFile("test.txt", fileBaseUrl: testUrl)
//  创建文件
    private func createFile(name:String,fileBaseUrl:NSURL){
        let manager = NSFileManager.defaultManager()
        
        let file = fileBaseUrl.URLByAppendingPathComponent(name)
        print("文件: \\(file)")
        let exist = manager.fileExistsAtPath(file.path!)
        if !exist {
            let data = NSData(base64EncodedString:"aGVsbG8gd29ybGQ=",options:.IgnoreUnknownCharacters)
            let createSuccess = manager.createFileAtPath(file.path!,contents:data,attributes:nil)
            print("文件创建结果: \\(createSuccess)")
        }
    }

6. 对文件进行复制
1).第一种方法:

let copyManager = NSFileManager.defaultManager()
        let homeDirectory = NSHomeDirectory()
        let fromUrl = homeDirectory + "/Documents/RookieString.txt"
        let toUrl = homeDirectory + "/Documents/copyed.txt"
        try! copyManager.copyItemAtPath(fromUrl, toPath: toUrl)
2).定位到用户文档目录:
let copyManager2 = NSFileManager.defaultManager()
        let copyUrlForDocument2 = copyManager2.URLsForDirectory( NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
        let copyUrl2 = copyUrlForDocument2[0] as NSURL
        // 将test.txt文件拷贝到文档目录根目录下的copyed.txt文件
        let fromUrl2 = copyUrl2.URLByAppendingPathComponent("/Documents/RookieString.txt")
        let toUrl2 = copyUrl2.URLByAppendingPathComponent("copyed.txt")
        try! copyManager2.copyItemAtURL(fromUrl2, toURL: toUrl2)

7. 移动文件夹
1).第一种方法:

let moveManager = NSFileManager.defaultManager()
        let moveHomeDirectory = NSHomeDirectory()
        let moveFromUrl = moveHomeDirectory + "/Documents/hangge.txt"
        let moveToUrl = moveHomeDirectory + "/Documents/moved"
        try! moveManager.moveItemAtPath(moveFromUrl, toPath: moveToUrl)
2).定位到用户文档目录:
let moveManager2 = NSFileManager.defaultManager()
        let moveHomeDirectory2 = moveManager2.URLsForDirectory( NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
        let moveUrl = moveHomeDirectory2[0] as NSURL
        
        let moveFromUrl2 = moveUrl.URLByAppendingPathComponent("test.txt")
        let moveToUrl2 = moveUrl.URLByAppendingPathComponent("copyed.txt")
        // 移动srcUrl中的文件(test.txt)到toUrl中(copyed.txt)
        try! moveManager2.moveItemAtURL(moveFromUrl2, toURL: moveToUrl2)

8. 删除文件
1).第一种方法:

let DelectManager = NSFileManager.defaultManager()
        let DelectFromUrl = NSHomeDirectory() + "/Documents/hangge.txt"
        try! DelectManager.removeItemAtPath(DelectFromUrl)
2).定位到用户文档目录:
let Delectmanager = NSFileManager.defaultManager()
        let DelecturlForDocument = Delectmanager.URLsForDirectory( NSSearchPathDirectory.DocumentDirectory,
                                                                   inDomains:NSSearchPathDomainMask.UserDomainMask)
        let Delecturl = DelecturlForDocument[0] as NSURL
        
        let DelecttoUrl = Delecturl.URLByAppendingPathComponent("copyed.txt")
        // 删除文档根目录下的toUrl路径的文件(copyed.txt文件)
        try! Delectmanager.removeItemAtURL(DelecttoUrl)

9. 删除目录下所有的文件

// 方法1:获取所有文件,然后遍历删除
        let DelectAllManager = NSFileManager.defaultManager()
        let DelectAllmyDirectory = NSHomeDirectory() + "/Documents/Files"
        let DelectAllfileArray:[AnyObject]? = DelectAllManager.subpathsAtPath(DelectAllmyDirectory)
        for fn in DelectAllfileArray!{
            try! DelectAllManager.removeItemAtPath(DelectAllmyDirectory + "/\\(fn)")
        }
        
        // 方法2:删除目录后重新创建该目录
        
        let DelectAllfileManager2 = NSFileManager.defaultManager()
        let DelectAllmyDirectory2 = NSHomeDirectory() + "/Documents/Files"
        try! DelectAllfileManager2.removeItemAtPath(DelectAllmyDirectory2)
        try! DelectAllfileManager2.createDirectoryAtPath(DelectAllmyDirectory2, withIntermediateDirectories: true,
                                                         attributes: nil)

10. 读取我们所建的文

 let manager = NSFileManager.defaultManager()
        let urlsForDocDirectory = manager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
        let docPath:NSURL = urlsForDocDirectory[0] as NSURL
        let file = docPath.URLByAppendingPathComponent("test.txt")
        
        //方法1
        let readHandler = try! NSFileHandle(forReadingFromURL:file)
        let data = readHandler.readDataToEndOfFile()
        let readString = NSString(data: data, encoding: NSUTF8StringEncoding)
        print("文件内容: \\(readString)")
        
        //方法2
        let data1 = manager.contentsAtPath(file.path!)
        let readString1 = NSString(data: data1!, encoding: NSUTF8StringEncoding)
        print("文件内容: \\(readString1)")

11. 在任意位置写入数据

let manager = NSFileManager.defaultManager()
        let urlsForDocDirectory = manager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
        let docPath:NSURL = urlsForDocDirectory[0] as NSURL
        let file = docPath.URLByAppendingPathComponent("test.txt")
        
        let string = "添加一些文字到文件末尾"
        let appendedData = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
        let writeHandler = try? NSFileHandle(forWritingToURL:file)
        writeHandler!.seekToEndOfFile()
        writeHandler!.writeData(appendedData!)
    }
    // MARK:-  文件权限判断
    private func fliesManagerPower(){
        let manager = NSFileManager.defaultManager()
        let urlsForDocDirectory = manager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
        let docPath:NSURL = urlsForDocDirectory[0] as NSURL
        let file = docPath.URLByAppendingPathComponent("test.txt")
        
        let readable = manager.isReadableFileAtPath(file.path!)
        print("可读: \\(readable)")
        let writeable = manager.isWritableFileAtPath(file.path!)
        print("可写: \\(writeable)")
        let executable = manager.isExecutableFileAtPath(file.path!)
        print("可执行: \\(executable)")
        let deleteable = manager.isDeletableFileAtPath(file.path!)
        print("可删除: \\(deleteable)")
        
        //         获取文件属性(创建时间,修改时间,文件大小,文件类型等信息)
        let manager1 = NSFileManager.defaultManager()
        let urlsForDocDirectory1 = manager1.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory,
                                                             inDomains:NSSearchPathDomainMask.UserDomainMask)
        let docPath1:NSURL = urlsForDocDirectory1[0] as NSURL
        let file1 = docPath1.URLByAppendingPathComponent("test.txt")
        
        let attributes = try? manager.attributesOfItemAtPath(file1.path!) //结果为AnyObject类型
        print("attributes: \\(attributes!)")

12. 文件权限判断

 let manager = NSFileManager.defaultManager()
        let urlsForDocDirectory = manager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
        let docPath:NSURL = urlsForDocDirectory[0] as NSURL
        let file = docPath.URLByAppendingPathComponent("test.txt")
        
        let readable = manager.isReadableFileAtPath(file.path!)
        print("可读: \\(readable)")
        let writeable = manager.isWritableFileAtPath(file.path!)
        print("可写: \\(writeable)")
        let executable = manager.isExecutableFileAtPath(file.path!)
        print("可执行: \\(executable)")
        let deleteable = manager.isDeletableFileAtPath(file.path!)
        print("可删除: \\(deleteable)")
        
        //         获取文件属性(创建时间,修改时间,文件大小,文件类型等信息)
        let manager1 = NSFileManager.defaultManager()
        let urlsForDocDirectory1 = manager1.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory,
                                                             inDomains:NSSearchPathDomainMask.UserDomainMask)
        let docPath1:NSURL = urlsForDocDirectory1[0] as NSURL
        let file1 = docPath1.URLByAppendingPathComponent("test.txt")
        
        let attributes = try? manager.attributesOfItemAtPath(file1.path!) //结果为AnyObject类型
        print("attributes: \\(attributes!)")

13. 获取文件属性(创建时间,修改时间,文件大小,文件类型等信息)

let manager = NSFileManager.defaultManager()
let urlsForDocDirectory = manager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory,
    inDomains:NSSearchPathDomainMask.UserDomainMask)
let docPath:NSURL = urlsForDocDirectory[0] **as** NSURL
let file = docPath.URLByAppendingPathComponent("test.txt")
 
let attributes = try? manager.attributesOfItemAtPath(file.path!) //结果为AnyObject类型
print("attributes: \\(attributes!)")

14. 文件/文件夹比较

 let manager = NSFileManager.defaultManager()
        let urlsForDocDirectory = manager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory,
                                                           inDomains:NSSearchPathDomainMask.UserDomainMask)
        let docPath:NSURL = urlsForDocDirectory[0] as NSURL
        let contents = try! manager.contentsOfDirectoryAtPath(docPath.path!)
        
        //下面比较前面两个文件是否内容相同(该方法也可以用来比较目录)
        let count = contents.count
        if count > 1 {
            let path1 = docPath.path! + "/" + (contents[0] as String)
            let path2 = docPath.path! + "/" + (contents[1] as String)
            let equal = manager.contentsEqualAtPath(path1,andPath:path2)
            print("比较结果: \\(equal)")
        }

以上就是文件管理中我们经常做的一些操作方法,如有错误之处,还请大神纠正指导_,后期学习笔记会不定期的更新博客上, 可以关注me一下.

参考学习博客:[航歌][1]

Swift学习笔记
Gupao