Computer >> Máy Tính >  >> Lập trình >> IOS

Làm cách nào để tạo tệp, ghi dữ liệu vào tệp và đọc dữ liệu từ tệp đó trên iOS?

Là một nhà phát triển phần mềm, chúng ta phải luôn biết cách xử lý tệp, ghi vào tệp, đọc từ tệp, v.v.

Trong bài này, chúng ta sẽ tìm hiểu giống nhau, chúng ta sẽ tạo một tệp và ghi dữ liệu vào tệp và sau đó đọc qua cùng một tệp.

Vì vậy, hãy bắt đầu,

Bước 1 - Tạo mới Xcode Project → Single View Application → đặt tên là “ReadingWritingFile”

Bước 2 - Mở ViewController.swift và thêm chức năng mới như hình bên dưới

public func createAndWriteFile() {
}

Bây giờ chúng ta sẽ tạo một tệp và sẽ in đường dẫn của tệp.

Bước 3 - Bên trong thêm chức năng createAndWriteFile

let fileName = "sample"
let documentDirectoryUrl = try! FileManager.default.url(
   for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true
)
let fileUrl = documentDirectoryUrl.appendingPathComponent(fileName).appendingPathExtension("txt")
// prints the file path
print("File path \(fileUrl.path)")

Bây giờ, hàm createAndWriteFile của bạn sẽ giống như bên dưới

public func createAndWriteFile() {
   let fileName = "sample"
   let documentDirectoryUrl = try! FileManager.default.url(
      for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true
   )
   let fileUrl = documentDirectoryUrl.appendingPathComponent(fileName).appendingPathExtension("txt")
   // prints the file path
   print("File path \(fileUrl.path)")
   //data to write in file.
   let stringData = "Hello Tutorials Point"
   do {
      try stringData.write(to: fileUrl, atomically: true, encoding: String.Encoding.utf8)
   } catch let error as NSError {
      print (error)
   }
}

Bây giờ chúng ta sẽ ghi vào tệp.

Thêm mã bên dưới vào chức năng hiện có

//data to write in file.
let stringData = "Hello Tutorials Point"
do {
   try stringData.write(to: fileUrl, atomically: true, encoding: String.Encoding.utf8)
} catch let error as NSError {
   print (error)
}

Bước 4 - Chức năng cuối cùng của bạn sẽ giống như bên dưới

// function to create file and write into the same.
public func createAndWriteFile() {
   let fileName = "sample"
   let documentDirectoryUrl = try! FileManager.default.url(
      for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true
   )
   let fileUrl = documentDirectoryUrl.appendingPathComponent(fileName).appendingPathExtension("txt")
   // prints the file path
   print("File path \(fileUrl.path)")
   //data to write in file.
   let stringData = "Hello Tutorials Point"
   do {
      try stringData.write(to: fileUrl, atomically: true, encoding: String.Encoding.utf8)
   } catch let error as NSError {
      print (error)
   }
}

Bước 5 - Chạy dự án bằng cách gọi phương thức mới từ viewDidLoad () và điều hướng đường dẫn tệp và xác thực nội dung.

Bước 6 - Bây giờ chúng ta sẽ đọc nội dung, hãy sao chép đoạn mã dưới đây vào cùng một chức năng

var readFile = ""
do {
   readFile = try String(contentsOf: fileUrl)
} catch let error as NSError {
   print(error)
}
print (readFile)

Và bạn đã hoàn thành,

Làm cách nào để tạo tệp, ghi dữ liệu vào tệp và đọc dữ liệu từ tệp đó trên iOS?

Bước 7 - Hoàn thành mã,

import UIKit
class ViewController: UIViewController {
   override func viewDidLoad() {
      super.viewDidLoad()
      // Do any additional setup after loading the view, typically from a nib.
      self.createReadAndWriteFile()
   }
   override func didReceiveMemoryWarning() {
      super.didReceiveMemoryWarning()
      // Dispose of any resources that can be recreated.
   }
   // function to create file and write into the same.
   public func createReadAndWriteFile() {
      let fileName = "sample"
      let documentDirectoryUrl = try! FileManager.default.url(
         for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true
         )
      let fileUrl = documentDirectoryUrl.appendingPathComponent(fileName).appendingPathExtension("txt")
      // prints the file path
      print("File path \(fileUrl.path)")
      //data to write in file.
      let stringData = "Hello Tutorials Point."
      do {
         try stringData.write(to: fileUrl, atomically: true, encoding: String.Encoding.utf8)
      } catch let error as NSError {
         print (error)
      }
      var readFile = ""
      do {
         readFile = try String(contentsOf: fileUrl)
      } catch let error as NSError {
         print(error)
      }
      print (readFile)
   }
}