ios开发经常会遇到读文件,写文件等,对文件和文件夹的操作,这时就可以使用NSFileManager,NSFileHandle等类来实现。
2,判断文件或文件夹是否存在
3
3,创建文件夹
下面总结了各种常用的操作:
1,遍历一个目录下的所有文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@H_502_62@
24
25
26
27
28
29
30
31
32
|
let
manager =
NSFileManager
.defaultManager()
urlForDocument = manager.
URLsForDirectory
(
NSSearchPathDirectory
.
DocumentDirectory
,inDomains:
NSSearchPathDomainMask
UserDomainMask
)
url = urlForDocument[0]
as
NSURL
contentsOfPath = try? manager.contentsOfDirectoryAtPath(url.path!)
//contentsOfPath:Optional([fold1,test1.txt])
print
(
"contentsOfPath: \(contentsOfPath)"
)
contentsOfURL = try? manager.contentsOfDirectoryAtURL(url,includingPropertiesForKeys:
nil
NSDirectoryEnumerationOptions
SkipsHiddenFiles
);
//contentsOfURL:Optional([file://Users/.../Application/.../Documents/fold1/,
"contentsOfURL: \(contentsOfURL)"
)
enumeratorAtPath = manager.enumeratorAtPath(url.path!)
//enumeratorAtPath:Optional([fold1,fold1/test2.txt,test1.txt])
"enumeratorAtPath: \(enumeratorAtPath?.allObjects)"
)
enumeratorAtURL = manager.enumeratorAtURL(url,errorHandler:
)
file://Users/.../Application/.../Documents/test1.txt])
"enumeratorAtURL: \(enumeratorAtURL?.allObjects)"
)
subPaths = manager.subpathsAtPath(url.path!)
//subPaths:Optional([fold1,test1.txt])
"subPaths: \(subPaths)"
)
|
fileManager =
.defaultManager()
filePath:
String
=
NSHomeDirectory
() +
"/Documents/hangge.txt"
var
exist = fileManager.fileExistsAtPath(filePath)
|
3,创建文件夹
方式1:
方式2:
6
1
2
3
4
5
6
|
let
myDirectory:
String
=
NSHomeDirectory
() +
"/Documents/myFolder/Files"
fileManager =
NSFileManager
.defaultManager()
//withIntermediateDirectories为ture表示路径中间如果有不存在的文件夹都会创建
try! fileManager.createDirectoryAtPath(myDirectory,
withIntermediateDirectories:
true
nil
)
|
func
createFolder(name:
NSURL
){
manager =
folder = baseUrl.
URLByAppendingPathComponent
(name,isDirectory:
)
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(
4,将对象写入文件
"folder"
可以通过writeToFile方法,可以创建文件并将对象写入,对象包括String,NSString,UIImage,NSArray,NSDictionary等。 (1)把String保存到文件
(2)把图片保存到文件路径下
(3)把NSArray保存到文件路径下 (4)把NSDictionary保存到文件路径下 5,创建文件
(1)方法1
(2)方法2 (1)方法1 (2)方法2
(1)方法1 (2)方法2 (1)方法1:获取所有文件,然后遍历删除 (2)方法2:删除目录后重新创建该目录
原文出自: www.hangge.com 转载请保留原文链接: http://www.hangge.com/blog/cache/detail_527.html 猜你在找的Swift相关文章 |