Swift3.0语言教程字符串与文件的数据转换,若是想要对字符串中的字符进行永久保存,能够将字符串中的字符写入到文件中。固然,开发者也能够将写入的内容进行读取,并转换为字符串。首先咱们来看如何将字符串中的字符写入到文件中,要想实现此功能,须要使用到NSString中的write(toFile:atomically:encoding:)方法,其语法形式以下:编码
func write(toFile path: String, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws
其中,参数说明以下:atom
【示例1-100】如下将字符串中的字符写入到File空文件中。spa
import Foundation var str=NSString(string:"All things are difficult before they are easy.") var path="/Users/mac/Desktop/File" //写入 do{ try str.write(toFile: path, atomically: true, encoding: String.Encoding.ascii.rawValue) }catch{ }
运行效果如图1.1所示。.net
图1.1 运行效果code
在此程序中咱们提到了空文件,此文件的建立须要实现如下几步:blog
(1)在Xcode的菜单中选择“Flie|New|File…”命令,弹出Choose a template for your new file:对话框,如图1.2所示。教程
图1.2 Choose a template for your new file:对话框ci
(2)选择macOS的Other中的Empty模板,单击Next按钮,弹出文件保存位置对话框,如图1.3所示。开发
图1.3 文件保存位置对话框文档
(3)输入文件名称,选择好文件保存的位置后,单击Create按钮,此时一个File空文件就建立好了,如图1.4所示。
图1.4 File文件
经过NSString能够将字符串中的字符写入到指定文件中,还能够将文件中的内容读取出来。读取文件内容须要使用到NSString中的的init(contentsOfFile:encoding:)方法,其语法形式以下:
convenience init(contentsOfFile path: String, encoding enc: UInt) throws
其中,path用来指定须要读取文件的路径,enc用来指定编码格式。
【示例1-101】如下将读取文件File中的内容。
import Foundation var path="/Users/mac/Desktop/File" var str:NSString?=nil //读取文件内容 do{ str=try NSString(contentsOfFile: path,encoding: String.Encoding.ascii.rawValue) }catch{ } print(str!)
运行结果以下:
All things are difficult before they are easy.
Swift3.0语言教程字符串与文件的数据转换