码迷,mamicode.com
首页 > 移动开发 > 详细

iOS开发——Swift篇&文件,文件夹操作

时间:2015-07-23 21:32:26      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:

文件,文件夹操作

ios开发经常会遇到读文件,写文件等,对文件和文件夹的操作,这时就可以使用NSFileManager,NSFileHandle等类来实现。
下面总结了各种常用的操作:
 
1,遍历一个目录下的所有文件
 1 //假设用户文档下有如下文件和文件夹[test1.txt,fold1/test2.txt]
 2 let manager = NSFileManager.defaultManager()
 3 let urlForDocument = manager.URLsForDirectory( NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
 4 let url = urlForDocument[0] as NSURL
 5 var error:NSErrorPointer = nil
 6  
 7 //(1)对指定路径执行浅搜索,返回指定目录路径下的文件、子目录及符号链接的列表
 8 let contentsOfPath = manager.contentsOfDirectoryAtPath(url.path!, error: error)
 9 //contentsOfPath:Optional([fold1, test1.txt])
10 println("contentsOfPath: \(contentsOfPath)")  
11  
12 //(2)类似上面的,对指定路径执行浅搜索,返回指定目录路径下的文件、子目录及符号链接的列表
13 let contentsOfURL = manager.contentsOfDirectoryAtURL(url, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, error: error);
14 //contentsOfURL:Optional([file://Users/.../Application/.../Documents/fold1/,
15 // file://Users/.../Application/.../Documents/test1.txt])
16 println("contentsOfURL: \(contentsOfURL)") 
17  
18 //(3)深度遍历,会递归遍历子文件夹(但不会递归符号链接)
19 let enumeratorAtPath = manager.enumeratorAtPath(url.path!)
20 //enumeratorAtPath:Optional([fold1, fold1/test2.txt, test1.txt])
21 println("enumeratorAtPath: \(enumeratorAtPath?.allObjects)")  
22  
23 //(4)类似上面的,深度遍历,会递归遍历子文件夹(但不会递归符号链接)
24 let enumeratorAtURL = manager.enumeratorAtURL(url, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler:nil)
25 //contentsOfURL:Optional([file://Users/.../Application/.../Documents/fold1/,
26 // file://Users/.../Application/.../Documents/fold1/test2.txt,
27 // file://Users/.../Application/.../Documents/test1.txt])
28 println("enumeratorAtURL: \(enumeratorAtURL?.allObjects)")
29  
30 //(5)深度遍历,会递归遍历子文件夹(包括符号链接,所以要求性能的话用enumeratorAtPath)
31 let subPaths = manager.subpathsAtPath(url.path!)
32 //subPaths:Optional([fold1, fold1/test2.txt, test1.txt])
33 println("subPaths: \(subPaths)")

 

 
2,判断文件或文件夹是否存在
 
 
let fileManager = NSFileManager.defaultManager()
let filePath:String = NSHomeDirectory() + "/Documents/hangge.txt"
var exist = fileManager.fileExistsAtPath(filePath)

 

3,创建文件夹 
方式1:
1 let myDirectory:String = NSHomeDirectory() + "/Documents/myFolder/Files"
2 let fileManager = NSFileManager.defaultManager()
3 var error:NSErrorPointer = nil
4 //withIntermediateDirectories为ture表示路径中间如果有不存在的文件夹都会创建
5 var isSuccess:Bool = fileManager.createDirectoryAtPath(myDirectory,
6     withIntermediateDirectories: true, attributes: nil, error: error)

 

方式2:
 1 func createFolder(name:String,baseUrl:NSURL){
 2     let manager = NSFileManager.defaultManager()
 3     var error:NSErrorPointer = nil
 4     let folder = baseUrl.URLByAppendingPathComponent(name, isDirectory: true)
 5     println("文件夹: \(folder)")
 6     let exist = manager.fileExistsAtPath(folder.path!)
 7     if !exist {
 8         let createSuccess = manager.createDirectoryAtURL(folder, withIntermediateDirectories: true, attributes: nil, error: error)
 9         println("文件夹创建结果: \(createSuccess)")
10     }
11 }
12  
13 //在文档目录下新建folder目录
14 let manager = NSFileManager.defaultManager()
15 let urlForDocument = manager.URLsForDirectory( NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
16 let url = urlForDocument[0] as NSURL
17 var error:NSErrorPointer = nil
18 createFolder("folder", baseUrl: url)

 

 
4,将对象写入文件
可以通过writeToFile方法,可以创建文件并将对象写入,对象包括String,NSString,UIImage,NSArray,NSDictionary等。
(1)把String保存到文件
1 let filePath:String = NSHomeDirectory() + "/Documents/hangge.txt"
2 var error:NSErrorPointer = nil
3 var info = "欢迎来到hange.com"
4 info.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding, error: error)

 

(2)把图片保存到文件路径下
1 let filePath:String = NSHomeDirectory() + "/Documents/hangge.png"
2 var image = UIImage(named: "apple.png")
3 var data:NSData = UIImagePNGRepresentation(image)
4 data.writeToFile(filePath, atomically: true)

 


(3)把NSArray保存到文件路径下
1 var array = NSArray(objects: "aaa","bbb","ccc")
2 let filePath:String = NSHomeDirectory() + "/Documents/array.plist"
3 array.writeToFile(filePath, atomically: true)

 


(4)把NSDictionary保存到文件路径下
1 var dictionary = NSDictionary(objects: ["111","222"], forKeys: ["aaa","bbb"])
2 let filePath:String = NSHomeDirectory() + "/Documents/dictionary.plist"
3 dictionary.writeToFile(filePath, atomically: true)

 


5,创建文件
 1 func createFile(name:String,fileBaseUrl:NSURL){
 2     let manager = NSFileManager.defaultManager()
 3     var error:NSErrorPointer = nil
 4      
 5     let file = fileBaseUrl.URLByAppendingPathComponent(name)
 6     println("文件: \(file)")
 7     let exist = manager.fileExistsAtPath(file.path!)
 8     if !exist {
 9         let data = NSData(base64EncodedString:"aGVsbG8gd29ybGQ=",options:.IgnoreUnknownCharacters)
10         let createSuccess = manager.createFileAtPath(file.path!,contents:data,attributes:nil)
11         println("文件创建结果: \(createSuccess)")
12     }
13 }
14  
15 //在文档目录下新建test.txt文件
16 let manager = NSFileManager.defaultManager()
17 let urlForDocument = manager.URLsForDirectory( NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
18 let url = urlForDocument[0] as NSURL
19 var error:NSErrorPointer = nil
20 createFile("test.txt", fileBaseUrl: url)
21 //createFile("folder/new.txt", fileBaseUrl: url)

 

 
6,复制文件 
(1)方法1
1 let fileManager = NSFileManager.defaultManager()
2 let homeDirectory = NSHomeDirectory()
3 var error:NSErrorPointer = nil
4 let srcUrl = homeDirectory + "/Documents/hangge.txt"
5 let toUrl = homeDirectory + "/Documents/copyed.txt"
6 fileManager.copyItemAtPath(srcUrl, toPath: toUrl, error: error)

 

(2)方法2
 1 // 定位到用户文档目录
 2 let manager = NSFileManager.defaultManager()
 3 let urlForDocument = manager.URLsForDirectory( NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
 4 let url = urlForDocument[0] as NSURL
 5 var error:NSErrorPointer = nil
 6  
 7 let contentsOfURL = manager.contentsOfDirectoryAtURL(url, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, error: error);
 8 // 将test.txt文件拷贝到文档目录根目录下的copyed.txt文件
 9 let srcUrl = url.URLByAppendingPathComponent("test.txt")
10 let toUrl = url.URLByAppendingPathComponent("copyed.txt")
11  
12 let copyItemSuccess = manager.copyItemAtURL(srcUrl, toURL: toUrl, error: error)
13 println("复制结果: \(copyItemSuccess)")

 

 
7,移动文件 
(1)方法1
1 let fileManager = NSFileManager.defaultManager()
2 let homeDirectory = NSHomeDirectory()
3 var error:NSErrorPointer = nil
4 let srcUrl = homeDirectory + "/Documents/hangge.txt"
5 let toUrl = homeDirectory + "/Documents/moved"
6 fileManager.moveItemAtPath(srcUrl, toPath: toUrl, error: error)

 

(2)方法2
 1 // 定位到用户文档目录
 2 let manager = NSFileManager.defaultManager()
 3 let urlForDocument = manager.URLsForDirectory( NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
 4 let url = urlForDocument[0] as NSURL
 5 var error:NSErrorPointer = nil
 6  
 7 let contentsOfURL = manager.contentsOfDirectoryAtURL(url, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, error: error);
 8 let srcUrl = url.URLByAppendingPathComponent("test.txt")
 9 let toUrl = url.URLByAppendingPathComponent("copyed.txt")
10 // 移动srcUrl中的文件(test.txt)到toUrl中(copyed.txt)
11 let moveItemSuccess = manager.moveItemAtURL(srcUrl, toURL: toUrl, error: error)

 

 
8,删除文件 
(1)方法1
1 let fileManager = NSFileManager.defaultManager()
2 let homeDirectory = NSHomeDirectory()
3 var error:NSErrorPointer = nil
4 let srcUrl = homeDirectory + "/Documents/hangge.txt"
5 fileManager.removeItemAtPath(srcUrl, error: error)

 

(2)方法2
 1 // 定位到用户文档目录
 2 let manager = NSFileManager.defaultManager()
 3 let urlForDocument = manager.URLsForDirectory( NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
 4 let url = urlForDocument[0] as NSURL
 5 var error:NSErrorPointer = nil
 6  
 7 let contentsOfURL = manager.contentsOfDirectoryAtURL(url, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, error: error);
 8 let toUrl = url.URLByAppendingPathComponent("copyed.txt")
 9 // 删除文档根目录下的toUrl路径的文件(copyed.txt文件)
10 let removeItemSuccess = manager.removeItemAtURL(toUrl, error: error)
11 println("删除结果: \(removeItemSuccess)")

 

 
9,删除目录下所有的文件
(1)方法1:获取所有文件,然后遍历删除
1 let fileManager = NSFileManager.defaultManager()
2 var error:NSErrorPointer = nil
3 var myDirectory = NSHomeDirectory() + "/Documents/Files"
4 var fileArray:[AnyObject]? = fileManager.subpathsAtPath(myDirectory)
5 for fn in fileArray!{
6     fileManager.removeItemAtPath(myDirectory + "/\(fn)", error: error)
7 }

 


(2)方法2:删除目录后重新创建该目录
1 let fileManager = NSFileManager.defaultManager()
2 var error:NSErrorPointer = nil
3 var myDirectory = NSHomeDirectory() + "/Documents/Files"
4 fileManager.removeItemAtPath(myDirectory, error: error)
5 fileManager.createDirectoryAtPath(myDirectory, withIntermediateDirectories: true,
6     attributes: nil, error: error)

 

10,读取文件
 1 let manager = NSFileManager.defaultManager()
 2 let urlsForDocDirectory = manager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
 3 let docPath:NSURL = urlsForDocDirectory[0] as NSURL
 4 let file = docPath.URLByAppendingPathComponent("test.txt")
 5  
 6 //方法1
 7 var readHandler = NSFileHandle(forReadingFromURL:file,error:nil)!
 8 var data = readHandler.readDataToEndOfFile()
 9 var readString = NSString(data: data, encoding: NSUTF8StringEncoding)
10 println("文件内容: \(readString)")
11 //方法2
12 let data = manager.contentsAtPath(file.path!)
13 var readString = NSString(data: data, encoding: NSUTF8StringEncoding)
14 println("文件内容: \(readString)")

 

 
11,在任意位置写入数据
1 let string = "添加一些文字到文件末尾"
2 let appendedData = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
3 let writeHandler = NSFileHandle(forWritingToURL:file,error:nil)!
4 writeHandler.seekToEndOfFile()
5 writeHandler.writeData(appendedData!)

 

 
12,文件权限判断
 1 let manager = NSFileManager.defaultManager()
 2 let urlsForDocDirectory = manager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
 3 let docPath:NSURL = urlsForDocDirectory[0] as NSURL
 4 let file = docPath.URLByAppendingPathComponent("test.txt")
 5  
 6 let readable = manager.isReadableFileAtPath(file.path!)
 7 println("可读: \(readable)")
 8 let writeable = manager.isWritableFileAtPath(file.path!)
 9 println("可写: \(writeable)")
10 let executable = manager.isExecutableFileAtPath(file.path!)
11 println("可执行: \(executable)")
12 let deleteable = manager.isDeletableFileAtPath(file.path!)
13 println("可删除: \(deleteable)")

 

 
13,获取文件属性(创建时间,修改时间,文件大小,文件类型等信息)
1 let manager = NSFileManager.defaultManager()
2 let urlsForDocDirectory = manager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
3 let docPath:NSURL = urlsForDocDirectory[0] as NSURL
4 let file = docPath.URLByAppendingPathComponent("test.txt")
5  
6 let attributes = manager.attributesOfItemAtPath(file.path!,error:nil) //结果为AnyObject类型
7 println("attributes: \(attributes!)")

 

 
14,文件/文件夹比较
 1 let manager = NSFileManager.defaultManager()
 2 let urlsForDocDirectory = manager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
 3 let docPath:NSURL = urlsForDocDirectory[0] as NSURL
 4 let contents = manager.contentsOfDirectoryAtPath(docPath.path!,error:nil)!
 5  
 6 //下面比较前面两个文件是否内容相同(该方法也可以用来比较目录)
 7 let count = contents.count
 8 if count > 1 {
 9     let path1 = docPath.path! + "/" + (contents[0] as String)
10     let path2 = docPath.path! + "/" + (contents[1] as String)
11     let equal = manager.contentsEqualAtPath(path1,andPath:path2)
12     println("比较结果: \(equal)")
13 }

 

 

iOS开发——Swift篇&文件,文件夹操作

标签:

原文地址:http://www.cnblogs.com/iCocos/p/4671479.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!