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語言教程字符串與文件的數據轉換