微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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
//假设用户文档下有如下文件文件夹[test1.txt,fold1/test2.txt]
let manager = NSFileManager .defaultManager()
urlForDocument = manager. URLsForDirectory ( NSSearchPathDirectory . DocumentDirectory ,inDomains: NSSearchPathDomainMask UserDomainMask )
url = urlForDocument[0] as NSURL
//(1)对指定路径执行浅搜索,返回指定目录路径下的文件、子目录及符号链接的列表
contentsOfPath = try? manager.contentsOfDirectoryAtPath(url.path!)
//contentsOfPath:Optional([fold1,test1.txt])
print ( "contentsOfPath: \(contentsOfPath)" )
//(2)类似上面的,对指定路径执行浅搜索,返回指定目录路径下的文件、子目录及符号链接的列表
contentsOfURL = try? manager.contentsOfDirectoryAtURL(url,includingPropertiesForKeys: nil ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,options: NSDirectoryEnumerationoptions SkipsHiddenFiles );
"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/test1.txt])
"enumeratorAtURL: \(enumeratorAtURL?.allObjects)" )
//(5)深度遍历,会递归遍历子文件夹(包括符号链接,所以要求性能的话用enumeratorAtPath)
subPaths = manager.subpathsAtPath(url.path!)
//subPaths:Optional([fold1,test1.txt])
"subPaths: \(subPaths)" )

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

3,创建文件
方式1:
1
2
3
4
5
6
let myDirectory: String = NSHomeDirectory () + "/Documents/myFolder/Files"
fileManager = NSFileManager .defaultManager()
//withIntermediateDirectories为ture表示路径中间如果有不存在的文件夹都会创建
try! fileManager.createDirectoryAtPath(myDirectory,
withIntermediateDirectories: true ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,attributes: nil )
方式2:
6
7
8
9
10
11
12
13
14
15
func createFolder(name: ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,baseUrl: 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 ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,inDomains: NSSearchPathDomainMask UserDomainMask )
url = urlForDocument[0] as NSURL
createFolder( "folder" ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,baseUrl: url)

4,将对象写入文件
可以通过writetoFile方法,可以创建文件并将对象写入,对象包括String,Nsstring,UIImage,NSArray,NSDictionary等。
(1)把String保存到文件
3
filePath: "/Documents/hangge.txt"
info = "欢迎来到hange.com"
try! info.writetoFile(filePath,atomically: ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,encoding: 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"ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,"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: ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,fileBaseUrl:
file = fileBaseUrl. (name)
"文件: \(file)" )
exist = manager.fileExistsAtPath(file.path!)
!exist {
data = (base64EncodedString: "aGVsbG8gd29ybGQ=" ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,options:. IgnoreUnkNownCharacters )
createSuccess = manager.createFileAtPath(file.path!,contents:data,monospace!important; min-height:inherit!important">)
"文件创建结果: \(createSuccess)" )
}
}
//在文档目录下新建test.txt文件
.defaultManager()
inDomains: )
NSURL
createFile( "test.txt" ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,fileBaseUrl: url)
//createFile("folder/new.txt",fileBaseUrl: url)

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
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:100%!important; font-family:Consolas,
NSURL
// 删除文档根目录下的toUrl路径的文件copyed.txt文件
try! manager.removeItemAtURL(toUrl)

9,删除目录下所有的文件
(1)方法1:获取所有文件,然后遍历删除
myDirectory ="/Documents/Files"
fileArray:[ AnyObject ]? = fileManager.subpathsAtPath(myDirectory)
for fn in fileArray!{
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( ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,allowLossyConversion: 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
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:100%!important; font-family:Consolas,
attributes = try? manager.attributesOfItemAtPath(file.path!) //结果为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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐