当前位置: 首页 > 工具软件 > Swift Lang > 使用案例 >

Swift 文件读取 和 写入

南宫喜
2023-12-01

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。。。

 类似资料: