Swift 文件读取 和 写入

Swift 文件读取 和 写入

1 文件的读取

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

2 文件的写入

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)!)

更新ing。。。

你可能感兴趣的:(iOS,swift,swift,iOS,文件读取,文件写入)