Save/load text file

Save to text file

To save text data in a text file, first create the path of the text file. Here, create a textFile.txt file in the Documents folder of your home directory and save the text data. Get the path to your home directory with NSHomeDirectory.

viewController.swift


let path = NSHomeDirectory() + "/Documents/textFile.txt"

Since saving the file may fail, it is necessary to incorporate it into error handling with do --try --catch.

If automatically is set to true, the file will be saved using a temporary file so that the file will not be damaged even if there is an abnormal termination during writing.

viewController.swift


let textData = textView.text
do {
 //Try to save text data
  try textData?.write(tofile: path, automatically: true, encoding : String.Encoding.utf8)
  print("success")

} catch let error as NSError{
 //Executed when try fails
  print("Failed to save: \(error)" ) 
}

Reading from a text file

The path of the file to be read is the same as the path of saving. Incorporate into error handling with do --try --catch as when saving

viewController.swift



do {
 //Try to read text data
let texData = try String(contentOfFile: path, encoding: String.Encoding.utf8)
  textView2 = textData
  print("success")

} catch let error as NSError{
 //Executed when try fails
  textView2.text = "Failed to read:\(error)"
  print("Read failure: \(error)" ) 
}

Check if the file exists

viewController.swift



//Make a file manager
let fileManager = FileManager.default
//Suspend if the specified file does not exist
guard (fileManager.fileExists(atPath: path) == true) else { return }

Recommended Posts

Save/load text file
JavaFX text
[Rails] views file creation # text is displayed