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
33
|
let manager = NSFileManager .defaultManager()
let urlForDocument = manager. URLsForDirectory ( NSSearchPathDirectory . DocumentDirectory , inDomains: NSSearchPathDomainMask . UserDomainMask )
let url = urlForDocument[0] as NSURL
var error: NSErrorPointer = nil
let contentsOfPath = manager.contentsOfDirectoryAtPath(url.path!, error: error)
println ( "contentsOfPath: \(contentsOfPath)" )
let contentsOfURL = manager.contentsOfDirectoryAtURL(url, includingPropertiesForKeys: nil , options: NSDirectoryEnumerationOptions . SkipsHiddenFiles , error: error);
println ( "contentsOfURL: \(contentsOfURL)" )
let enumeratorAtPath = manager.enumeratorAtPath(url.path!)
println ( "enumeratorAtPath: \(enumeratorAtPath?.allObjects)" )
let enumeratorAtURL = manager.enumeratorAtURL(url, includingPropertiesForKeys: nil , options: NSDirectoryEnumerationOptions . SkipsHiddenFiles , errorHandler: nil )
println ( "enumeratorAtURL: \(enumeratorAtURL?.allObjects)" )
let subPaths = manager.subpathsAtPath(url.path!)
println ( "subPaths: \(subPaths)" )
|
2,判断文件或文件夹是否存在
1
2
3
|
let fileManager = NSFileManager .defaultManager()
let 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"
let fileManager = NSFileManager .defaultManager()
var error: NSErrorPointer = nil
var isSuccess: Bool = fileManager.createDirectoryAtPath(myDirectory,
withIntermediateDirectories: true , attributes: nil , error: error)
|
方式2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
func createFolder(name: String ,baseUrl: NSURL ){
let manager = NSFileManager .defaultManager()
var error: NSErrorPointer = nil
let folder = baseUrl. URLByAppendingPathComponent (name, isDirectory: true )
println ( "文件夹: \(folder)" )
let exist = manager.fileExistsAtPath(folder.path!)
if !exist {
let createSuccess = manager.createDirectoryAtURL(folder, withIntermediateDirectories: true , attributes: nil , error: error)
println ( "文件夹创建结果: \(createSuccess)" )
}
}
let manager = NSFileManager .defaultManager()
let urlForDocument = manager. URLsForDirectory ( NSSearchPathDirectory . DocumentDirectory , inDomains: NSSearchPathDomainMask . UserDomainMask )
let url = urlForDocument[0] as NSURL
var error: NSErrorPointer = nil
createFolder( "folder" , baseUrl: url)
|
4,将对象写入文件
可以通过writeToFile方法,可以创建文件并将对象写入,对象包括String,NSString,UIImage,NSArray,NSDictionary等。
(1)把String保存到文件
1
2
3
4
|
let filePath: String = NSHomeDirectory () + "/Documents/hangge.txt"
var error: NSErrorPointer = nil
var info = "欢迎来到hange.com"
info.writeToFile(filePath, atomically: true , encoding: NSUTF8StringEncoding , error: error)
|
(2)把图片保存到文件路径下
1
2
3
4
|
let filePath: String = NSHomeDirectory () + "/Documents/hangge.png"
var image = UIImage (named: "apple.png" )
var data: NSData = UIImagePNGRepresentation (image)
data.writeToFile(filePath, atomically: true )
|
(3)把NSArray保存到文件路径下
1
2
3
|
var array = NSArray (objects: "aaa" , "bbb" , "ccc" )
let filePath: String = NSHomeDirectory () + "/Documents/array.plist"
array.writeToFile(filePath, atomically: true )
|
(4)把NSDictionary保存到文件路径下
1
2
3
|
var dictionary = NSDictionary (objects: [ "111" , "222" ], forKeys: [ "aaa" , "bbb" ])
let filePath: String = NSHomeDirectory () + "/Documents/dictionary.plist"
dictionary.writeToFile(filePath, atomically: true )
|
5,创建文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
func createFile(name: String ,fileBaseUrl: NSURL ){
let manager = NSFileManager .defaultManager()
var error: NSErrorPointer = nil
let file = fileBaseUrl. URLByAppendingPathComponent (name)
println ( "文件: \(file)" )
let exist = manager.fileExistsAtPath(file.path!)
if !exist {
let data = NSData (base64EncodedString: "aGVsbG8gd29ybGQ=" ,options:. IgnoreUnknownCharacters )
let createSuccess = manager.createFileAtPath(file.path!,contents:data,attributes: nil )
println ( "文件创建结果: \(createSuccess)" )
}
}
let manager = NSFileManager .defaultManager()
let urlForDocument = manager. URLsForDirectory ( NSSearchPathDirectory . DocumentDirectory , inDomains: NSSearchPathDomainMask . UserDomainMask )
let url = urlForDocument[0] as NSURL
var error: NSErrorPointer = nil
createFile( "test.txt" , fileBaseUrl: url)
|
6,复制文件
(1)方法1
1
2
3
4
5
6
|
let fileManager = NSFileManager .defaultManager()
let homeDirectory = NSHomeDirectory ()
var error: NSErrorPointer = nil
let srcUrl = homeDirectory + "/Documents/hangge.txt"
let toUrl = homeDirectory + "/Documents/copyed.txt"
fileManager.copyItemAtPath(srcUrl, toPath: toUrl, error: error)
|
(2)方法2
1
2
3
4
5
6
7
8
9
10
11
12
13
|
let manager = NSFileManager .defaultManager()
let urlForDocument = manager. URLsForDirectory ( NSSearchPathDirectory . DocumentDirectory , inDomains: NSSearchPathDomainMask . UserDomainMask )
let url = urlForDocument[0] as NSURL
var error: NSErrorPointer = nil
let contentsOfURL = manager.contentsOfDirectoryAtURL(url, includingPropertiesForKeys: nil , options: NSDirectoryEnumerationOptions . SkipsHiddenFiles , error: error);
let srcUrl = url. URLByAppendingPathComponent ( "test.txt" )
let toUrl = url. URLByAppendingPathComponent ( "copyed.txt" )
let copyItemSuccess = manager.copyItemAtURL(srcUrl, toURL: toUrl, error: error)
println ( "复制结果: \(copyItemSuccess)" )
|
7,移动文件
(1)方法1
1
2
3
4
5
6
|
let fileManager = NSFileManager .defaultManager()
let homeDirectory = NSHomeDirectory ()
var error: NSErrorPointer = nil
let srcUrl = homeDirectory + "/Documents/hangge.txt"
let toUrl = homeDirectory + "/Documents/moved"
fileManager.moveItemAtPath(srcUrl, toPath: toUrl, error: error)
|
(2)方法2
1
2
3
4
5
6
7
8
9
10
11
|
let manager = NSFileManager .defaultManager()
let urlForDocument = manager. URLsForDirectory ( NSSearchPathDirectory . DocumentDirectory , inDomains: NSSearchPathDomainMask . UserDomainMask )
let url = urlForDocument[0] as NSURL
var error: NSErrorPointer = nil
let contentsOfURL = manager.contentsOfDirectoryAtURL(url, includingPropertiesForKeys: nil , options: NSDirectoryEnumerationOptions . SkipsHiddenFiles , error: error);
let srcUrl = url. URLByAppendingPathComponent ( "test.txt" )
let toUrl = url. URLByAppendingPathComponent ( "copyed.txt" )
let moveItemSuccess = manager.moveItemAtURL(srcUrl, toURL: toUrl, error: error)
|
8,删除文件
(1)方法1
1
2
3
4
5
|
let fileManager = NSFileManager .defaultManager()
let homeDirectory = NSHomeDirectory ()
var error: NSErrorPointer = nil
let srcUrl = homeDirectory + "/Documents/hangge.txt"
fileManager.removeItemAtPath(srcUrl, error: error)
|
(2)方法2
1
2
3
4
5
6
7
8
9
10
11
|
let manager = NSFileManager .defaultManager()
let urlForDocument = manager. URLsForDirectory ( NSSearchPathDirectory . DocumentDirectory , inDomains: NSSearchPathDomainMask . UserDomainMask )
let url = urlForDocument[0] as NSURL
var error: NSErrorPointer = nil
let contentsOfURL = manager.contentsOfDirectoryAtURL(url, includingPropertiesForKeys: nil , options: NSDirectoryEnumerationOptions . SkipsHiddenFiles , error: error);
let toUrl = url. URLByAppendingPathComponent ( "copyed.txt" )
let removeItemSuccess = manager.removeItemAtURL(toUrl, error: error)
println ( "删除结果: \(removeItemSuccess)" )
|
9,删除目录下所有的文件
(1)方法1:获取所有文件,然后遍历删除
1
2
3
4
5
6
7
|
let fileManager = NSFileManager .defaultManager()
var error: NSErrorPointer = nil
var myDirectory = NSHomeDirectory () + "/Documents/Files"
var fileArray:[ AnyObject ]? = fileManager.subpathsAtPath(myDirectory)
for fn in fileArray!{
fileManager.removeItemAtPath(myDirectory + "/\(fn)" , error: error)
}
|
(2)方法2:删除目录后重新创建该目录
1
2
3
4
5
6
|
let fileManager = NSFileManager .defaultManager()
var error: NSErrorPointer = nil
var myDirectory = NSHomeDirectory () + "/Documents/Files"
fileManager.removeItemAtPath(myDirectory, error: error)
fileManager.createDirectoryAtPath(myDirectory, withIntermediateDirectories: true ,
attributes: nil , error: error)
|
10,读取文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
let manager = NSFileManager .defaultManager()
let urlsForDocDirectory = manager. URLsForDirectory ( NSSearchPathDirectory . DocumentDirectory , inDomains: NSSearchPathDomainMask . UserDomainMask )
let docPath: NSURL = urlsForDocDirectory[0] as NSURL
let file = docPath. URLByAppendingPathComponent ( "test.txt" )
var readHandler = NSFileHandle (forReadingFromURL:file,error: nil )!
var data = readHandler.readDataToEndOfFile()
var readString = NSString (data: data, encoding: NSUTF8StringEncoding )
println ( "文件内容: \(readString)" )
let data = manager.contentsAtPath(file.path!)
var readString = NSString (data: data, encoding: NSUTF8StringEncoding )
println ( "文件内容: \(readString)" )
|
11,在任意位置写入数据
1
2
3
4
5
|
let string = "添加一些文字到文件末尾"
let appendedData = string.dataUsingEncoding( NSUTF8StringEncoding , allowLossyConversion: true )
let writeHandler = NSFileHandle (forWritingToURL:file,error: nil )!
writeHandler.seekToEndOfFile()
writeHandler.writeData(appendedData!)
|
12,文件权限判断
1
2
3
4
5
6
7
8
9
10
11
12
13
|
let manager = NSFileManager .defaultManager()
let urlsForDocDirectory = manager. URLsForDirectory ( NSSearchPathDirectory . DocumentDirectory , inDomains: NSSearchPathDomainMask . UserDomainMask )
let docPath: NSURL = urlsForDocDirectory[0] as NSURL
let file = docPath. URLByAppendingPathComponent ( "test.txt" )
let readable = manager.isReadableFileAtPath(file.path!)
println ( "可读: \(readable)" )
let writeable = manager.isWritableFileAtPath(file.path!)
println ( "可写: \(writeable)" )
let executable = manager.isExecutableFileAtPath(file.path!)
println ( "可执行: \(executable)" )
let deleteable = manager.isDeletableFileAtPath(file.path!)
println ( "可删除: \(deleteable)" )
|
13,获取文件属性(创建时间,修改时间,文件大小,文件类型等信息)
1
2
3
4
5
6
7
|
let manager = NSFileManager .defaultManager()
let urlsForDocDirectory = manager. URLsForDirectory ( NSSearchPathDirectory . DocumentDirectory , inDomains:
|
|
请发表评论