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

前端之家收集整理的这篇文章主要介绍了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
@H_502_62@ 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 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 nil )
方式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" //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
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( 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
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

猜你在找的Swift相关文章