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
//假设用户文档下有如下文件和文件夹[test1.txt,fold1/test2.txt]
let manager = NSFileManager.defaultManager()
let urlForDocument = manager.URLsForDirectory( NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)
let url = urlForDocument[0] as NSURL
var error:NSErrorPointer = nil
 
//(1)对指定路径执行浅搜索,返回指定目录路径下的文件、子目录及符号链接的列表
let contentsOfPath = manager.contentsOfDirectoryAtPath(url.path!, error: error)
//contentsOfPath:Optional([fold1, test1.txt])
println("contentsOfPath: \(contentsOfPath)"
 
//(2)类似上面的,对指定路径执行浅搜索,返回指定目录路径下的文件、子目录及符号链接的列表
let contentsOfURL = manager.contentsOfDirectoryAtURL(url, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, error: error);
println("contentsOfURL: \(contentsOfURL)")
 
//(3)深度遍历,会递归遍历子文件夹(但不会递归符号链接)
let enumeratorAtPath = manager.enumeratorAtPath(url.path!)
//enumeratorAtPath:Optional([fold1, fold1/test2.txt, test1.txt])
println("enumeratorAtPath: \(enumeratorAtPath?.allObjects)"
 
//(4)类似上面的,深度遍历,会递归遍历子文件夹(但不会递归符号链接)
let enumeratorAtURL = manager.enumeratorAtURL(url, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler:nil)
println("enumeratorAtURL: \(enumeratorAtURL?.allObjects)")
 
//(5)深度遍历,会递归遍历子文件夹(包括符号链接,所以要求性能的话用enumeratorAtPath)
let subPaths = manager.subpathsAtPath(url.path!)
//subPaths:Optional([fold1, fold1/test2.txt, test1.txt])
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
//withIntermediateDirectories为ture表示路径中间如果有不存在的文件夹都会创建
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)")
    }
}
 
//在文档目录下新建folder目录
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)")
    }
}
 
//在文档目录下新建test.txt文件
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)
//createFile("folder/new.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);
// 将test.txt文件拷贝到文档目录根目录下的copyed.txt文件
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")
// 移动srcUrl中的文件(test.txt)到toUrl中(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")
// 删除文档根目录下的toUrl路径的文件(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")
 
//方法1
var readHandler = NSFileHandle(forReadingFromURL:file,error:nil)!
var data = readHandler.readDataToEndOfFile()
var readString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("文件内容: \(readString)")
//方法2
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:NSSearchPathDomainMask.UserDomainMask)
let docPath:NSURL = urlsForDocDirectory[0] as NSURL
let file = docPath.URLByAppendingPathComponent("test.txt")
 
let attributes = manager.attributesOfItemAtPath(file.path!,error:nil) //结果为AnyObject类型
println("attributes: \(attributes!)")

14,文件/文件夹比较

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 contents = manager.contentsOfDirectoryAtPath(docPath.path!,error:nil)!
 
//下面比较前面两个文件是否内容相同(该方法也可以用来比较目录)
let count = contents.count
if count > 1 {
    let path1 = docPath.path! + "/" + (contents[0] as String)
    let path2 = docPath.path! + "/" + (contents[1] as String)
    let equal = manager.contentsEqualAtPath(path1,andPath:path2)
    println("比较结果: \(equal)")
}

Swift - 文件,文件夹操作大全的更多相关文章

  1. iOS开发——Swift篇&文件,文件夹操作

    文件,文件夹操作   ios开发经常会遇到读文件,写文件等,对文件和文件夹的操作,这时就可以使用NSFileManager,NSFileHandle等类来实现. 下面总结了各种常用的操作:   1,遍 ...

  2. Python文件操作大全,随机删除文件夹内的任意文件

     在读文件的时候往往需要遍历文件夹,python的os.path包含了很多文件.文件夹操作的方法: os.path.abspath(path) #返回绝对路径os.path.basename(path ...

  3. Java 文件操作大全

    Java 文件操作大全 //1.创建文件夹 //import java.io.*; File myFolderPath = new File(str1); try { if (!myFolderPat ...

  4. python文件、文件夹操作OS模块

    转自:python文件.文件夹操作OS模块   '''一.python中对文件.文件夹操作时经常用到的os模块和shutil模块常用方法.1.得到当前工作目录,即当前Python脚本工作的目录路径: ...

  5. 【整理】C#文件操作大全(SamWang)

    [整理]C#文件操作大全(SamWang) 文件与文件夹操作主要用到以下几个类: 1.File类: 提供用于创建.复制.删除.移动和打开文件的静态方法,并协助创建 FileStream 对象. msd ...

  6. 【转】C#添加修改删除文件文件夹大全

    [转]C#添加修改删除文件文件夹大全 C#添加修改删除文件文件夹大全 StreamWriter sw = File.AppendText(Server.MapPath(".")+& ...

  7. [No000083]文件与文件夹操作

    #region Folder option 文件夹操作 /// <summary> /// 指定目录是否存在 /// </summary> /// <param name ...

  8. PHP 文件夹操作「复制、删除、查看大小」递归实现

    PHP虽然提供了 filesize.copy.unlink 等文件操作的函数,但是没有提供 dirsize.copydir.rmdirs 等文件夹操作的函数(rmdir也只能删除空目录).所以只能手动 ...

  9. 【整理】C#文件操作大全(SamWang)<转>

    文件与文件夹操作主要用到以下几个类: 1.File类: 提供用于创建.复制.删除.移动和打开文件的静态方法,并协助创建 FileStream 对象. msdn:http://msdn.microsof ...

随机推荐

  1. 以libevent网络库为引:网络通信和多线程

    1. windows下编译及使用libevent  http://www.cnblogs.com/luxiaoxun/p/3603399.html 2.  <<libevent学习资料&g ...

  2. 用eclipse编写Android程序时怎样生成apk文件

    转载请注明出处:http://blog.csdn.net/ns_code/article/details/16828449 APK是Android Package的缩写,即Android安装包.通过将 ...

  3. 三、nginx301跳转302跳转

    301跳转设置: server { listen 80; server_name downcc.com; rewrite ^/(.*) http://www.downcc.com/$1 permane ...

  4. 01-Foundation简介、NSObject、copy、NSString

    目录: 一.Foundation常用类 二.Foundation简介 三.NSObject 四.NSString 回到顶部 一.Foundation常用类 1 NSObject.NSString.NS ...

  5. Visual Studio 2012的新技术特性

    前言 我更换了VS2012开发工具,那么它有什么特性呢? [caption id="attachment_1235" align="alignnone" wid ...

  6. mysql 表级锁

    表级锁:分为读锁和写锁: lock tables table_name read;//其他事务只能读,不能加写锁,要等待更新. SESSION 50 执行: mysql> update test ...

  7. Mixtile LOFT

    日前,国内电子原型类开发团队Mixtile(深圳致趣科技)新推出的 Mixtile LOFT套件,受到业内著名的海外科技网站CNXSoft的关注和报道. 如果要阅读相关的原文报道,可点击这里.下面摘录 ...

  8. Testin_百度百科

    Testin_百度百科     Testin    编辑    目录     1测试平台     2三大特性    #1 真机终端云,节省测试设备购买租赁成本#2 自动化测试,节省测试人员成本及时间# ...

  9. textarea内容有换行时存入数据库丢失问题的解决 (转载)

    http://blog.csdn.net/zhang_j_h/article/details/44563167 存入: function GetInputData(id, cmd) { var pos ...

  10. Oracle、DB2、MySql、SQLServer JDBC驱动

    四种数据库JDBC驱动,还列出了连接的Class驱动名和Url Pattern,DB2包括Type 2.Type 3和Type 4三种模式.注意驱动包名称的大小写. Oralce连接驱动包名和URL ...