從文字檔案讀取和寫入字串


在 Swift 中,您可以使用 String 類的 String(contentsOfFile:) 和 write(toFile:atomically:encoding:) 方法從文字檔案讀取和寫入字串。您將看到一些 Swift 中檔案讀取和寫入的示例。

String(contentsOfFile:)

String 類提供了一個從檔案內容建立字串的類方法。此方法是一個初始化程式,必須提供檔案路徑。例如,您可以透過將路徑傳遞給主包來讀取本地檔案的內容。此過程將返回一個包含檔案內容的新字串。

請記住,如果內容或路徑無效或出於任何其他原因,此方法可能會返回 nil。可以使用 try-catch 塊來處理這種情況。

write(toFile:atomically:encoding:)

在此方法中,String 類的例項將字串的內容寫入檔案。該方法採用三個引數:

toFile − 要將字串寫入的檔案的路徑。

atomically − 一個布林值,確定是否應以原子方式寫入檔案。如果設定為 true,則將檔案寫入臨時位置,然後將其重新命名為最終位置。這可以幫助防止在寫入操作期間發生故障時資料丟失。

encoding − 將字串寫入檔案時使用的編碼。預設值為 .utf8。

以下是有關如何從文字檔案讀取字串的示例

請注意,在開始讀取檔案之前。這裡,我們在 Xcode 專案中添加了一個名為“example.txt”的檔案。我們將讀取同一個檔案。在該文字檔案中,我們添加了以下字串內容:

Lorem Ipsum 僅僅是印刷和排版行業的虛擬文字。

自從 1500 年代,當一位不知名的印刷工取走了一版印刷樣張,並將其重新排列以製作一本印刷樣張書籍時,Lorem Ipsum 就一直是該行業的標準虛擬文字。

示例

將從 example.txt 檔案中讀取相同的字串內容。

func readString() {
   do {
      // creating a path from the main bundle
      if let bundlePath = Bundle.main.path(forResource: "example.txt", ofType: nil) {
         let stringContent = try String(contentsOfFile: bundlePath)
         print("Content string starts from here-----")
         print(stringContent)
         print("End at here-----")
      }
   } catch {
      print(error)
   }
}

輸出

Content string starts from here-----
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
End at here-----

以下是如何將字串寫入文字檔案的示例

要將字串內容寫入檔案,我們將使用上面示例中使用的相同檔案。

示例

func writeString() {
   do {
      // creating path from main bundle
      if let bundlePath = Bundle.main.path(forResource: "example.txt", ofType: nil) {
            
         let stringToWrite = "This is a string to write to a file."
         try? stringToWrite.write(toFile: bundlePath, atomically: true, encoding: .utf8)
            
         let stringContent = try String(contentsOfFile: bundlePath)
         print("Content string starts from here-----")
         print(stringContent)
         print("End at here-----")
      }
   } catch {
      print(error)
   }
}

輸出

Content string starts from here-----
This is a string to write to a file.
End at here-----

請注意,bundlePath 變數是包中檔案的路徑。如果檔案不在包中,您也可以使用自定義路徑。

請記住,contentsOfFile: 和 write(toFile:atomically:encoding:) 方法可能會丟擲錯誤,因此建議使用 try? 或 try! 關鍵字或 do-catch 語句來處理它們。

結論

上述方法用於將檔案的內容讀取到字串中,然後將字串寫入檔案。

您應該注意,當您處理檔案時,需要處理錯誤。這是因為在讀取或寫入檔案時,出現錯誤的可能性更大。您可以提供自定義路徑或包中的路徑。此外,您可以使用 FileManager 提供檔案系統的路徑。

更新於: 2023 年 2 月 28 日

2K+ 閱讀量

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.