import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.copyFile() self.moveFile() self.removeFile() self.removeFolder() self.listFolder() } func copyFile() { //获得文件管理对象,它的主要功能包括:读取文件中的数据、向一个文件中写入数据、删除或复制文件、移动文件、比较另个文件的内容等 let fileManager = FileManager.default let sourceUrl = NSHomeDirectory() + "/Documents/swift.txt" let targetUrl = NSHomeDirectory() + "/Documents/swift_bak.txt"//表示文件被复制后的目标位置 do {//创建一个异常捕捉语句,用于复制一个文件 try fileManager.copyItem(atPath: sourceUrl, toPath: targetUrl) print("Success to copy file.") } catch { print("Failed to copy file.") } } func moveFile() { //获得文件管理对象,它的主要功能包括:读取文件中的数据、向一个文件中写入数据、删除或复制文件、移动文件、比较另个文件的内容等 let fileManager = FileManager.default let sourceUrl = NSHomeDirectory() + "/Documents/products.plist" let targetUrl = NSHomeDirectory() + "/Documents/backUp"//表示文件被移动后的目标位置 do { try fileManager.moveItem(atPath: sourceUrl, toPath: targetUrl) print("Success to move file.") } catch { print("Failed to move file.") } } func removeFile() { let fileManager = FileManager.default let sourceUrl = NSHomeDirectory() + "/Documents/Pic.png" do { try fileManager.removeItem(atPath: sourceUrl) print("Success to remove file.") } catch { print("Failed to remove file.") } } func removeFolder() { let fileManager = FileManager.default let folder = NSHomeDirectory() + "/Documents/bak" let files:[AnyObject]? = fileManager.subpaths(atPath: folder) as [AnyObject]? for file in files! {//遍历 do { try fileManager.removeItem(atPath: folder + "/(file)") print("Success to remove folder") } catch { print("Failed to remove folder") } } } func listFolder() { let manager = FileManager.default let url = NSHomeDirectory() + "/Documents/"//文档目录 let contents = manager.enumerator(atPath: url) print("contents:(String(describing: contents?.allObjects))") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }