Swift3.0語言教程字串與檔案的資料轉換

大學霸發表於2016-11-18

Swift3.0語言教程字串與檔案的資料轉換

Swift3.0語言教程字串與檔案的資料轉換,如果想要對字串中的字元進行永久儲存,可以將字串中的字元寫入到檔案中。當然,開發者也可以將寫入的內容進行讀取,並轉換為字串。首先我們來看如何將字串中的字元寫入到檔案中,要想實現此功能,需要使用到NSString中的write(toFile:atomically:encoding:)方法,其語法形式如下:

func write(toFile path: String, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws

其中,引數說明如下:

q  path:用來指定寫入到檔案的路徑。

q  useAuxiliaryFile:用來指定是否先將字串寫入到輔助文件。

q  enc:用來指定編碼格式。

【示例1-100】以下將字串中的字元寫入到File空檔案中。

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


1.1  執行效果

在此程式中我們提到了空檔案,此檔案的建立需要實現以下幾步:

1)在Xcode的選單中選擇“Flie|New|File…”命令,彈出Choose a template for your new file:對話方塊,如圖1.2所示。


1.2  Choose a template for your new file:對話方塊

2)選擇macOSOther中的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語言教程字串與檔案的資料轉換

相關閱讀:Swift3.0語言教程字串轉換為數字值

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29597077/viewspace-2128695/,如需轉載,請註明出處,否則將追究法律責任。

相關文章