Swift 文件读取 和 写入

文件的读取

读取本地txt资源:

//读取本地txt资源
let path = Bundle.main.path(forResource:"mapStr", ofType:"txt")
let text = try! String(contentsOfFile:path!, encoding: String.Encoding.utf8)

是读取沙盒内的文件:

//读取沙盒内的文件
let url:URL?=URL.init(string:NSHomeDirectory() + "/Documents/test.txt");
let text = try! String(contentsOfFile:url!.relativePath, encoding: String.Encoding.utf8)

文件的写入

let msg = "需要写入的资源"
let fileName = "学习笔记.text"

let fileManager = FileManager.default
let file = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
let path = file! + fileName

fileManager.createFile(atPath: path, contents:nil, attributes:nil)

let handle = FileHandle(forWritingAtPath:path)
handle?.write(msg.data(using: String.Encoding.utf8)!)