Swift - 文件,文件夹 *** 作大全

Swift - 文件,文件夹 *** 作大全,第1张

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

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

3,创建文件夹 方式1: @H_404_81@ letmyDirectory:String=NSHomeDirectory() +"/documents/myFolder/files" fileManager =NSfileManager.defaultManager()//withIntermediateDirectorIEs为ture表示路径中间如果有不存在的文件夹都会创建try! fileManager.createDirectoryAtPath(myDirectory,withIntermediateDirectorIEs:truenil)
1 2 3 4 5 6
方式2: 6 7 8 9 10 11 12 13 14 15
func createFolder(name: NSURL ){ manager = folder = baseUrl. URLByAppendingPathComponent (name,isDirectory: ) print ( "文件夹: \(folder)" ) exist = manager.fileExistsAtPath(folder.path!) if !exist { try! manager.createDirectoryAtURL(folder,withIntermediateDirectorIEs: ) } } //在文档目录下新建folder目录 .defaultManager() urlFordocument = manager. URLsForDirectory ( NSSearchPathDirectory . documentDirectory NSSearchPathDomainMask UserDomainMask ) url = urlFordocument[0] as NSURL createFolder( "folder" 4,将对象写入文件
可以通过writetofile方法,可以创建文件并将对象写入,对象包括String,Nsstring,UIImage,NSArray,NSDictionary等。
(1)把String保存到文件 3
filePath: "/documents/hangge.txt" info = "欢迎来到hange.com" try! info.writetofile(filePath,atomically: NSUTF8StringEnCoding )

(2)把图片保存到文件路径下 4
"/documents/hangge.png" image = UIImage (named: "apple.png" ) data: NSData UIImagePNGRepresentation (image!)! data.writetofile(filePath,monospace!important; min-height:inherit!important">)

(3)把NSArray保存到文件路径下 array =NSArray(objects:"aaa""bbb""ccc") "/documents/array.pList" array.writetofile(filePath,monospace!important; min-height:inherit!important">)

(4)把NSDictionary保存到文件路径下 dictionary =NSDictionary(objects: ["111""222"],forKeys: []) "/documents/dictionary.pList" dictionary.writetofile(filePath,monospace!important; min-height:inherit!important">)

5,创建文件 15 16 17 18 19 20
createfile(name: file = fileBaseUrl. (name) "文件: \(file)" ) exist = manager.fileExistsAtPath(file.path!) !exist { data = (base64EncodedString: "aGVsbG8gd29ybGQ=" IgnoreUnkNownCharacters ) createSuccess = manager.createfileAtPath(file.path!,contents:data,monospace!important; min-height:inherit!important">) "文件创建结果: \(createSuccess)" ) } } //在文档目录下新建test.txt文件 .defaultManager() inDomains: ) NSURL createfile( "test.txt"

6,复制文件 (1)方法1 5
.defaultManager() homeDirectory = () srcUrl = homeDirectory + "/documents/hangge.txt" toUrl = homeDirectory + "/documents/copyed.txt" try! fileManager.copyItemAtPath(srcUrl,topath: toUrl)

(2)方法2 10
// 定位到用户文档目录 NSURL // 将test.txt文件拷贝到文档目录根目录下的copyed.txt文件 srcUrl = url. toUrl = url. "copyed.txt" try! manager.copyItemAtURL(srcUrl,toURL: toUrl)

7,移动文件
(1)方法1 "/documents/moved" try! fileManager.moveItemAtPath(srcUrl,topath: toUrl)

(2)方法2 9
) // 移动srcUrl中的文件(test.txt)到toUrl中(copyed.txt) try! manager.moveItemAtURL(srcUrl,toURL: toUrl)

8,删除文件
(1)方法1 try! fileManager.removeItemAtPath(srcUrl)

(2)方法2 9,删除目录下所有的文件
(1)方法1:获取所有文件,然后遍历删除
myDirectory ="/documents/files" fileArray:[AnyObject]? = fileManager.subpathsAtPath(myDirectory) forfninfileArray!{ try! fileManager.removeItemAtPath(myDirectory +"/\(fn)"}

(2)方法2:删除目录后重新创建该目录 try! fileManager.removeItemAtPath(myDirectory) attributes:)
10,读取文件 urlsForDocDirectory = manager.docPath:= urlsForDocDirectory[0]NSURL file = docPath.//方法1 readHandler = try!NSfileHandle(forReadingFromURL:file) data = readHandler.readDataToEndOffile() readString =Nsstring(data: data,249)!important; border:0px!important; bottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:0px 1em!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; wIDth:auto!important; min-height:inherit!important"> "文件内容: \(readString)" //方法2 data = manager.contentsAtPath(file.path!) (data: data!,monospace!important; min-height:inherit!important">) )

11,在任意位置写入数据 string ="添加一些文字到文件末尾" appendedData = string.dataUsingEnCoding(writeHandler = try?(forWritingToURL:file) writeHandler!.seekToEndOffile() writeHandler!.writeData(appendedData!)

12,文件权限判断 13
readable = manager.isReadablefileAtPath(file.path!) "可读: \(readable)" writeable = manager.isWritablefileAtPath(file.path!) "可写: \(writeable)" executable = manager.isExecutablefileAtPath(file.path!) "可执行: \(executable)" ) deleteable = manager.isDeletablefileAtPath(file.path!) "可删除: \(deleteable)" )

13,获取文件属性(创建时间,修改时间,文件大小,文件类型等信息) 8
//结果为AnyObject类型 "attributes: \(attributes!)" )

14,文件/文件夹比较 14
contents = try! manager.contentsOfDirectoryAtPath(docPath.path!) //下面比较前面两个文件是否内容相同(该方法也可以用来比较目录) count = contents.count count > 1 { path1 = docPath.path! + "/" + (contents[0] as path2 = docPath.path! + + (contents[1] equal = manager.contentsEqualAtPath(path1,andpath:path2) "比较结果: \(equal)" }

原文出自: www.hangge.com 转载请保留原文链接: http://www.hangge.com/blog/cache/detail_527.html 总结

以上是内存溢出为你收集整理的Swift - 文件,文件夹 *** 作大全全部内容,希望文章能够帮你解决Swift - 文件,文件夹 *** 作大全所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1080882.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)