ios开发经常会遇到读文件,写文件等,对文件和文件夹的操作,这时就可以使用NSFileManager,NSFileHandle等类来实现。
2,判断文件或文件夹是否存在
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
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)"
)
|
3
fileManager =
.defaultManager()
filePath:
String
=
NSHomeDirectory
() +
"/Documents/hangge.txt"
var
exist = fileManager.fileExistsAtPath(filePath)
|
3,创建文件夹
方式1:
方式2:
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
)
|
6
7
8
9
10
11
12
13
14
15
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.
@H_502_459@url = urlForDocument[0]
URLsForDirectory
(
NSSearchPathDirectory
.
DocumentDirectory
NSSearchPathDomainMask
UserDomainMask
)
as
NSURL
createFolder(
"folder"
4,将对象写入文件
|