当前位置:网站首页>Swift basic FileManager (file management)
Swift basic FileManager (file management)
2022-07-26 06:09:00 【Feng Hanxu】
I always feel that what I write is not technology , But feelings , One tutorial after another is the trace of one's own journey . Success with expertise is the most replicable , I hope my path will make you less detours , I hope I can help you erase the dust of knowledge , I hope I can help you clarify the context of knowledge , I hope there will be you and me on the top of technology in the future .
Preface
Swift Basics FileManager( file management ) Download link
FileManager It is inevitable to use in project development , for example : I'm developing company music app You will need to save the downloaded songs . So record it today FileManager Use .
On the subject
1、 obtain Documentation Directory path
The most basic thing of file management is to get the directory of files , Get the directory of the file , The method to be called is the scope to be searched later .
open func urls(for directory: FileManager.SearchPathDirectory, in domainMask: FileManager.SearchPathDomainMask) -> [URL]
The system provides us with two important parameters :
directory: The name of the file to search
domainMask: Search in that fuzzy range
for example :
// TODO: obtain Documentation Directory path
let domainsArray = FileManager.default.urls(for:.documentDirectory, in: .userDomainMask)
let domainsPath = domainsArray[0] as URL
print(domainsPath)


The following provides the file box simulation path commonly used for searching
1.1. SearchPathDirectory Optional parameters for searching directories
applicationDirectory : stay applications Search under directory .
demoApplicationDirectory : stay applications/Demo Search under the directory of .
developerApplicationDirectory : stay Developer/Applications Search under directory .
adminApplicationDirectory : stay Applications/Utilities Search under directory .
libraryDirectory : stay Library Search under directory .
developerDirectory : stay Developer Search under directory , Not just a developer .
userDirectory : Search under the user's home directory .
documentationDirectory : stay Documentation Search under directory .
documentDirectory : stay Documents Search under directory .
coreServiceDirectory : stay System/Library/CoreServices Search under directory .
autosavedInformationDirectory : Auto saved document location search (Documents/Autosaved)
desktopDirectory : Search the user desktop .
cachesDirectory : Search in the local buffer directory (Library/Caches)
applicationSupportDirectory : Search under directories supported by local applications (Library/Application Support).
downloadsDirectory : Download locally downloads Catalog .
inputMethodsDirectory : Search under the input method directory (Library/Input Methods).
moviesDirectory : Search the user movie directory (~/Movies).
musicDirectory : Search the user's music directory (~/Music).
picturesDirectory: Search in the user image directory (~/Pictures).
printerDescriptionDirectory : Local to the system PPDs Search under directory (Library/Printers/PPDs).
sharedPublicDirectory : Search under the local user sharing directory (~/Public).
preferencePanesDirectory : Search in the preferences directory of the system (Library/PreferencePanes).
itemReplacementDirectory : For use with NSFileManager's URLForDirectory:inDomain:appropriateForURL:create:error:
allApplicationsDirectory : Apply all paths that can happen .
allLibrariesDirectory : All directories where resources can occur .
1.2. SearchPathDomainMask Optional parameters of fuzzy search in path field
userDomainMask : User's home directory path domain search .
localDomainMask : Current device local path domain search .
networkDomainMask : Path domain search of network sharing .
systemDomainMask : System path domain search provided by Apple .
allDomainsMask : Path field search for all the above situations .
2、 Get the file name under the path
let homePath = NSHomeDirectory()
// TODO: Get the file name under the path
let contentsOfPath = try? FileManager.default.contentsOfDirectory(atPath: homePath + "/Documents")
print(contentsOfPath as Any)
/** Output results : Optional(["music", ".DS_Store", "fenghanxu", "downloads"]) */
The search results shown in the figure below 
3、 Get the path of all files under the specified path URL
// TODO: Get the path of all files under the specified path URL
let contentsOfUrl = try? FileManager.default.contentsOfDirectory(at: URL.init(string: NSHomeDirectory() + "/Documents")!, includingPropertiesForKeys: [URLResourceKey.creationDateKey], options: .skipsSubdirectoryDescendants)
print(contentsOfUrl as Any)

4、 Depth traversal of all files under the specified path
// TODO: Depth traversal of all files under the specified path
let allFiel = FileManager.default.enumerator(atPath: NSHomeDirectory() + "/Documents")
print(allFiel?.allObjects as Any)
/** Output results :Optional([music, music/.DS_Store, music/javaScript.html, .DS_Store, fenghanxu, fenghanxu/.DS_Store, fenghanxu/xxx.dmg, downloads, downloads/.DS_Store, downloads/arm64.dmg]) */
perhaps
// Another way to traverse files in depth
let subPath = FileManager.default.subpaths(atPath: NSHomeDirectory() + "/Documents")
print(subPath as Any)
/** Output result : Optional([music, music/xxx.dmg, .DS_Store, fenghanxu, fenghanxu/.DS_Store, fenghanxu/xxx.dmg, downloads, downloads/.DS_Store, downloads/arm64.dmg]) */



5、 Convert the specified file into Data Binary stream data
// TODO: Convert the specified file into Data Binary stream data
let data = FileManager.default.contents(atPath: NSHomeDirectory() + "/Documents/fenghanxu/xxx.dmg")
print(data!)
/** Output results :Optional("12308244 bytes") */

6、 create a file
// TODO: create a file
let isFile = FileManager.default.createFile(atPath: NSHomeDirectory() + "/Documents/MyFile", contents: nil, attributes: nil)
print(isFile)
/** Output results : true Indicates that the creation was successful ; false Indicates creation failed */
The following picture is the result of printing :
Here is the effect :
let data = "i love swift".data(using: .utf8)
let isFile = FileManager.default.createFile(atPath: NSHomeDirectory() + "/Documents/MyFile.txt", contents: data, attributes: nil)
print(isFile)
/** Output results : true Indicates that the creation was successful ; false Indicates creation failed */
The following picture is the result of printing :
Here is the effect :
7、 Judge whether the file exists
// TODO: Judge whether the file exists
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)
/** Output results : true Indicates presence ; false Does not exist */


8、 Determine file permissions
// TODO: Determine whether the file is readable
let isRead = FileManager.default.isReadableFile(atPath: NSHomeDirectory() + "/Documents/MyFile.txt")
print("isRead: \(isRead)")//isRead: true
// TODO: Judge whether the document is writable
let isWrite = FileManager.default.isWritableFile(atPath: NSHomeDirectory() + "/Documents/MyFile.txt")
print("isWrite: \(isWrite)")//isWrite: true
// TODO: Determine whether the file is an executable file
let isExecutable = FileManager.default.isExecutableFile(atPath: NSHomeDirectory() + "/Documents/MyFile.txt")
print("isExecutable: \(isExecutable)")//isExecutable: false
// TODO: Judge whether the file can be deleted
let isDele = FileManager.default.isDeletableFile(atPath: NSHomeDirectory() + "/Documents/MyFile.txt")
print("isDele: \(isDele)")//isDele: true
9、 Get the local name of the file and the name set of all paths of the file
// TODO: Return the local display name of the file
let disName = FileManager.default.displayName(atPath: NSHomeDirectory() + "/Documents/MyFile.txt")
print(disName)
// TODO: Get the names of all files in the path
let componentsDisName = FileManager.default.componentsToDisplay(forPath: NSHomeDirectory() + "/Documents")
print(componentsDisName as Any)
/** Output results : Optional(["edy - data ", "Users", "edy", "Library", "Developer", "CoreSimulator", "Devices", "792DE238-7207-4A66-AB82-9E5BFEE2EF8F", "data", "Containers", "Data", "Application", "108D7874-63DC-4F14-BFBF-E176E1793520", "Documents"]) */

10 、 Write and save data
// MARK: The writing of file data
let info = "i love swift"
try! info.write(toFile: NSHomeDirectory() + "/Documents/MyFile.txt", atomically: true, encoding: .utf8)
// MARK: Save the array
let arraySave = NSArray.init(arrayLiteral: "a","b","c")
arraySave.write(toFile: NSHomeDirectory() + "/Documents/MyFilePlist.plist", atomically: true)
// MARK: Save the dictionary
let dictionSave = NSDictionary.init(dictionaryLiteral: ("A","ccc"),("B","bb"),("C","bbx"))
dictionSave.write(toFile: NSHomeDirectory() + "/Documents/MyFilePlist.plist", atomically: true)
// MARK: take Data preservation
let imagData = UIImage.init(named: "example.jpg")!.pngData()
try? imagData?.write(to: URL.init(fileURLWithPath: NSHomeDirectory() + "/Documents/MyPicture.jpg"))

11 、 Copy of documents 、 Move 、 Delete 、 Read operation
// MARK: Copy of documents ( Be careful : The file to be copied , If there is . Copy will fail )
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: File movement
let MoveStartFilePath = NSHomeDirectory() + "/Documents/MyFileCopy.txt"
let MoveToFilePath = NSHomeDirectory() + "/Documents/test/MyFileCopy.txt"
try? FileManager.default.moveItem(atPath: MoveStartFilePath, toPath: MoveToFilePath)

// MARK: Delete file
let DeleFilePath = NSHomeDirectory() + "/Documents/test/MyFileCopy.txt"
try! FileManager.default.removeItem(atPath: DeleFilePath)

// MARK: Data reading
let readDataPath = NSHomeDirectory() + "/Documents/MyFile.txt"
let dataInfo = FileManager.default.contents(atPath: readDataPath)
let readStr = String.init(data: dataInfo!, encoding: .utf8)
print(readStr!)
Print the results :
12 、 Get file attributes and basic file information
// MARK: Get the properties of the file
let attributes = try! FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory() + "/Documents/MyFile.txt")
print(attributes)
/** Output results [__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] */
// Get some basic information about files
let CreateData = attributes[FileAttributeKey.creationDate]
let FileSzie = attributes[FileAttributeKey.systemSize]
print(CreateData as Any)// nil
print(FileSzie as Any)// Optional(250685575168)

13、 Get the path of the current domain and change the file path ( No effect )
// MARK: Get the current path of the file
let CurrentPath = FileManager.default.currentDirectoryPath
print(CurrentPath)
// MARK: Change of file path
let exchangePath = "Documents"
let isExchangePath = FileManager.default.changeCurrentDirectoryPath(exchangePath)
print(isExchangePath)
14 、 Comparison of files or folders
Just go back to true. Not the same false
// MARK: Comparison of documents
let oneFilePath = NSHomeDirectory() + "/Documents/MyFile.txt"
let otherFilePath = NSHomeDirectory() + "/Documents/MyFilePlist.plist"
let isEqual = FileManager.default.contentsEqual(atPath: oneFilePath, andPath: otherFilePath)
print(isEqual)

Just go back to true. Not the same false
// Folder comparison
let FilePath = NSHomeDirectory() + "/Documents/test"
let FilePathOne = NSHomeDirectory() + "/Documents/test1"
let isEqualFile = FileManager.default.contentsEqual(atPath: FilePath, andPath: FilePathOne)
print(isEqualFile)

边栏推荐
- Flex layout
- Intelligent fire protection application based on fire GIS system
- 招标信息获取
- L. Link with Level Editor I dp
- Calling mode and execution sequence of JS
- Matlab 向量与矩阵
- 金仓数据库 KingbaseES SQL 语言参考手册 (8. 函数(十))
- 光量子里程碑:6分钟内解决3854个变量问题
- Optical quantum milestone: 3854 variable problems solved in 6 minutes
- WebAPI整理
猜你喜欢

Balanced binary tree (AVL)~

日志收集分析平台搭建-1-环境准备

语法泛化三种可行方案介绍

Youwei low code: Brick life cycle component life cycle

Convolutional neural network (III) - target detection
![[(SV & UVM) knowledge points encountered in written interview] ~ phase mechanism](/img/19/32206eb6490c2a5a7a8e746b5003c1.png)
[(SV & UVM) knowledge points encountered in written interview] ~ phase mechanism

Mysql45 speak in simple terms index

Amd zen4 game God u reached 208mb cache within this year, which is unprecedented

光量子里程碑:6分钟内解决3854个变量问题

Embedded sharing collection 14
随机推荐
Leetcode:934. The shortest Bridge
[the most complete and detailed] ten thousand words explanation: activiti workflow engine
Workflow activiti5.13 learning notes (I)
Knowledge precipitation I: what does an architect do? What problems have been solved
Understanding the mathematical essence of machine learning
[highly available MySQL solution] centos7 configures MySQL master-slave replication
Convolutional neural network (IV) - special applications: face recognition and neural style transformation
The time complexity of two recursive entries in a recursive function
Interview questions for software testing is a collection of interview questions for senior test engineers, which is exclusive to the whole network
【Day_06 0423】把字符串转换成整数
对接微信支付(二)统一下单API
1.12 Web开发基础
Convolutional neural network (II) - deep convolutional network: case study
英语句式参考纯享版 - 定语从句
Mobile web
Mysql45 talking about infrastructure: how is an SQL query executed?
PHP 多任务秒级定时器的实现方法
Embedded sharing collection 15
EM and REM
Ganglia installation and deployment process