一直觉得自己写的不是技术,而是情怀,一个个的教程是自己这一路走来的痕迹。靠专业技能的成功是最具可复制性的,希望我的这条路能让你们少走弯路,希望我能帮你们抹去知识的蒙尘,希望我能帮你们理清知识的脉络,希望未来技术之巅上有你们也有我。
前言
Swift 基础 FileManager(文件管理)下载链接
FileManager在项目开发中难免会用到,例如:我正在开发公司的音乐app就会用到保存下载下来的歌曲。所以今天记录一下FileManager的使用。
正题
1、获取Documentation 目录路径
文件管理肯定最基础的就是获取文件的目录,获取文件的目录,在调用的方法是以后需要执行搜索的范围。
open func urls(for directory: FileManager.SearchPathDirectory, in domainMask: FileManager.SearchPathDomainMask) -> [URL]
系统提供给我们需要两个重要的参数:
directory: 需要搜索的文件名称
domainMask: 在那个模糊范围里面搜索
例如:
// Todo: 获取 Documentation 目录路径
let domainsArray = FileManager.default.urls(for:.documentDirectory, in: .userDomainMask)
let domainsPath = domainsArray[0] as URL
print(domainsPath)
下面提供一下平时常用搜索的文件盒模拟路径
1.1. SearchPathDirectory 搜索目录的可选参数
applicationDirectory : 在 applications 目录下搜索。
demoApplicationDirectory : 在 applications/Demo 的目录下搜索。
developerApplicationDirectory : 在 Developer/Applications 目录下搜索。
adminApplicationDirectory : 在 Applications/Utilities 目录下搜索。
libraryDirectory :在 Library 目录下搜索。
developerDirectory : 在 Developer 目录下搜索,不只是一个开发者。
userDirectory : 在用户的主目录下搜索。
documentationDirectory : 在 Documentation 目录下搜索。
documentDirectory : 在 Documents 目录下搜索。
coreServiceDirectory : 在 System/Library/CoreServices 目录下搜索。
autosaved@R_653_4045@ionDirectory : 自动保存的文档位置搜索 (Documents/Autosaved)
desktopDirectory : 在用户桌面搜索。
cachesDirectory : 在本地缓冲目录在搜索(Library/Caches)
applicationSupportDirectory :本地应用所支持的目录下搜索(Library/Application Support)。
downloadsDirectory : 本地下载downloads目录。
inputMethodsDirectory :在输入方法目录下搜索(Library/Input Methods)。
moviesDirectory : 在用户电影目录搜索(~/Movies)。
musicDirectory : 在用户音乐目录搜索(~/Music)。
picturesDirectory: 在用户图片目录搜索(~/Pictures)。
printerDescriptionDirectory : 在系统本地PPDs目录下搜索(Library/Printers/PPDs)。
sharedPublicDirectory : 在本地用户分享目录下搜索(~/Public)。
preferencePanesDirectory : 在系统的偏好设置目录在搜索(Library/PreferencePanes)。
itemReplacementDirectory : For use with NSFileManager's URLForDirectory:inDomain:appropriateForURL:create:error:
allApplicationsDirectory :应用能够发生的所有路径 。
allLibrariesDirectory : 资源可以发生的所有目录 。
1.2. SearchPathDomainMask 路径领域的模糊搜索的可选参数
userDomainMask : 用户的主目录路径领域搜索。
localDomainMask : 当前设备本地路径领域搜索。
networkDomainMask :网络共享的路径领域搜索。
systemDomainMask : 由苹果提供的系统路径领域搜索。
allDomainsMask : 上述所有情况的路径领域搜索。
2、获取路径下的文件名字
let homePath = NSHomeDirectory()
// Todo: 获取路径下的文件名字
let contentsOfPath = try? FileManager.default.contentsOfDirectory(atPath: homePath + "/Documents")
print(contentsOfPath as Any)
/**
输出结果: Optional(["music",".DS_Store","fenghanxu","downloads"])
*/
如下图的搜索结果
3、 获取指定路径下的所有文件的路径URL
// Todo: 获取指定路径下的所有文件的路径URL
let contentsOfUrl = try? FileManager.default.contentsOfDirectory(at: URL.init(string: NSHomeDirectory() + "/Documents")!, includingPropertiesForKeys: [URLResourceKey.creationDateKey], options: .skipssubdirectoryDescendants)
print(contentsOfUrl as Any)
4、 深度遍历指定路径下的所有文件
// Todo: 深度遍历指定路径下的所有文件
let allFiel = FileManager.default.enumerator(atPath: NSHomeDirectory() + "/Documents")
print(allFiel?.allObjects as Any)
/**
输出结果:Optional([music,music/.DS_Store,music/javaScript.html,.DS_Store,fenghanxu,fenghanxu/.DS_Store,fenghanxu/xxx.dmg,downloads,downloads/.DS_Store,downloads/arm64.dmg])
*/
或者
// 另一种深度遍历文件的方法
let subPath = FileManager.default.subpaths(atPath: NSHomeDirectory() + "/Documents")
print(subPath as Any)
/**
输出的结果:
Optional([music,music/xxx.dmg,downloads/arm64.dmg])
*/
5、 把指定文件的转换成 Data 二进制流数据
// Todo: 把指定文件的转换成 Data 二进制流数据
let data = FileManager.default.contents(atPath: NSHomeDirectory() + "/Documents/fenghanxu/xxx.dmg")
print(data!)
/**
输出结果:Optional("12308244 bytes")
*/
6、 创建文件
// Todo: 创建文件
let isFile = FileManager.default.createFile(atPath: NSHomeDirectory() + "/Documents/MyFile", contents: nil, attributes: nil)
print(isFile)
/**
输出结果: true 表示创建成功 ; false 表示创建失败
*/
下面图片是打印的结果:
@H_815_502@
下面是效果图:
let data = "i love swift".data(using: .utf8)
let isFile = FileManager.default.createFile(atPath: NSHomeDirectory() + "/Documents/MyFile.txt", contents: data, attributes: nil)
print(isFile)
/**
输出结果: true 表示创建成功 ; false 表示创建失败
*/
下面图片是打印的结果:
下面是效果图:
7、判断文件是否存在
// Todo: 判断文件是否存在
var isSave = FileManager.default.fileExists(atPath: NSHomeDirectory() + "/Documents/MyFile.txt")
print(isSave)
var directory = ObjCBool(true)
isSave = FileManager.default.fileExists(atPath: NSHomeDirectory() + "/Documents/MyFile.txt", isDirectory: &directory)
print(isSave)
/**
输出结果: true 表示存在 ; false 表示不存在
*/
8、判断文件的权限
// Todo: 判断文件是否可读
let isRead = FileManager.default.isReadableFile(atPath: NSHomeDirectory() + "/Documents/MyFile.txt")
print("isRead: \(isRead)")//isRead: true
// Todo: 判断文件是否可写
let isWrite = FileManager.default.isWritableFile(atPath: NSHomeDirectory() + "/Documents/MyFile.txt")
print("isWrite: \(isWrite)")//isWrite: true
// Todo: 判断文件是否是可执行文件
let isExecutable = FileManager.default.isExecutableFile(atPath: NSHomeDirectory() + "/Documents/MyFile.txt")
print("isExecutable: \(isExecutable)")//isExecutable: false
// Todo: 判断文件是否可以删除
let isDele = FileManager.default.isDeletableFile(atPath: NSHomeDirectory() + "/Documents/MyFile.txt")
print("isDele: \(isDele)")//isDele: true
9、获取文件的本地名字和文件所有路径的名字集合
// Todo: 返回文件的本地显示名字
let disName = FileManager.default.displayName(atPath: NSHomeDirectory() + "/Documents/MyFile.txt")
print(disName)
// Todo: 获取路径下的所有文件的名字
let componentsdisName = FileManager.default.componentsTodisplay(forPath: NSHomeDirectory() + "/Documents")
print(componentsdisName as Any)
/**
输出结果:
Optional(["edy - 数据","Users","edy","Library","Developer","CoreSimulator","Devices","792DE238-7207-4A66-AB82-9E5BFEE2EF8F","data","Containers","Data","Application","108D7874-63DC-4F14-BFBF-E176E1793520","Documents"])
*/
10 、 数据的写入和保存
// MARK: 文件数据的写入
let info = "i love swift"
try! info.write(toFile: NSHomeDirectory() + "/Documents/MyFile.txt", atomically: true, encoding: .utf8)
// MARK: 将数组保存
let arraySave = NSArray.init(arrayLiteral: "a","b","c")
arraySave.write(toFile: NSHomeDirectory() + "/Documents/MyFilePlist.plist", atomically: true)
// MARK: 将字典保存
let dictionSave = NSDictionary.init(dictionaryLiteral: ("A","ccc"),("B","bb"),("C","bbx"))
dictionSave.write(toFile: NSHomeDirectory() + "/Documents/MyFilePlist.plist", atomically: true)
// MARK: 将Data 保存
let imagData = UIImage.init(named: "example.jpg")!.pngData()
try? imagData?.write(to: URL.init(fileURLWithPath: NSHomeDirectory() + "/Documents/MyPicture.jpg"))
11 、文件的复制、移动、删除、读取 操作
// MARK: 文件的复制(注意:将要复制出的文件,如果存在。将复制失败)
let startFilePath = NSHomeDirectory() + "/Documents/MyFile.txt"
let toFilePath = NSHomeDirectory() + "/Documents/MyFilecopy.txt"
try? FileManager.default.copyItem(at:URL.init(fileURLWithPath: startFilePath) , to: URL.init(fileURLWithPath: toFilePath))
// MARK: 文件的移动
let MoveStartFilePath = NSHomeDirectory() + "/Documents/MyFilecopy.txt"
let MovetoFilePath = NSHomeDirectory() + "/Documents/test/MyFilecopy.txt"
try? FileManager.default.moveItem(atPath: MoveStartFilePath, toPath: MovetoFilePath)
// MARK: 删除文件
let DeleFilePath = NSHomeDirectory() + "/Documents/test/MyFilecopy.txt"
try! FileManager.default.removeItem(atPath: DeleFilePath)
// MARK: 数据的读取
let readDataPath = NSHomeDirectory() + "/Documents/MyFile.txt"
let dataInfo = FileManager.default.contents(atPath: readDataPath)
let readStr = String.init(data: dataInfo!, encoding: .utf8)
print(readStr!)
打印结果:
12 、 获取文件的属性和基本一些文件信息
// MARK: 获取文件的属性
let attributes = try! FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory() + "/Documents/MyFile.txt")
print(attributes)
/**
输出结果
[__C.NSFileAttributeKey(_rawValue: NSFileSystemFreeNodes): 224441360,__C.NSFileAttributeKey(_rawValue: NSFileSystemSize): 250685575168,__C.NSFileAttributeKey(_rawValue: NSFileSystemNumber): 16777220,__C.NSFileAttributeKey(_rawValue: NSFileSystemFreeSize): 22982795264,__C.NSFileAttributeKey(_rawValue: NSFileSystemNodes): 228901731]
*/
// 获取一些文件的基本信息
let CreateData = attributes[FileAttributeKey.creationDate]
let FileSzie = attributes[FileAttributeKey.systemSize]
print(CreateData as Any)// nil
print(FileSzie as Any)// Optional(250685575168)
13、当前域的路径获取和文件路径的变更(搞不出效果)
// MARK: 获取文件的当前路径
let CurrentPath = FileManager.default.currentDirectoryPath
print(CurrentPath)
// MARK: 文件路径的变更
let exchangePath = "Documents"
let isExchangePath = FileManager.default.changeCurrentDirectoryPath(exchangePath)
print(isExchangePath)
14 、 文件或者文件夹的比较
一样返回true。不一样返回false
// MARK: 文件的比较
let oneFilePath = NSHomeDirectory() + "/Documents/MyFile.txt"
let otherFilePath = NSHomeDirectory() + "/Documents/MyFilePlist.plist"
let isEqual = FileManager.default.contentsEqual(atPath: oneFilePath, andpath: otherFilePath)
print(isEqual)
一样返回true。不一样返回false
// 文件夹的比较
let FilePath = NSHomeDirectory() + "/Documents/test"
let FilePathOne = NSHomeDirectory() + "/Documents/test1"
let isEqualFile = FileManager.default.contentsEqual(atPath: FilePath, andpath: FilePathOne)
print(isEqualFile)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。