소프트웨어 개발자인 우리는 파일을 가지고 노는 방법, 파일에 쓰는 방법, 파일에서 읽는 방법 등을 항상 알고 있어야 합니다.
이 포스트에서 우리는 파일을 생성하고 파일에 데이터를 쓰고 나중에 같은 파일을 읽을 것입니다.
시작하겠습니다.
1단계 − 새 Xcode 프로젝트 생성 → 단일 보기 응용 프로그램 → 이름을 "ReadingWritingFile"로 지정
2단계 − ViewController.swift를 열고 아래와 같이 새 기능을 추가합니다.
public func createAndWriteFile() {
} 이제 파일을 만들고 파일의 경로를 인쇄합니다.
3단계 − 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)") 이제 createAndWriteFile 함수는 다음과 같아야 합니다.
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)
}
} 이제 파일에 쓸 것입니다.
기존 함수에 아래 코드 추가
//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)
} 4단계 − 최종 함수는 다음과 같아야 합니다.
// 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)
}
} 5단계 − viewDidLoad()에서 새 메서드를 호출하여 프로젝트를 실행하고 파일 경로를 탐색하고 내용을 확인합니다.
6단계 − 이제 내용을 읽을 것입니다. 아래 코드를 동일한 함수에 복사합니다.
var readFile = ""
do {
readFile = try String(contentsOf: fileUrl)
} catch let error as NSError {
print(error)
}
print (readFile) 완료되었습니다.

7단계 − 완전한 코드,
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)
}
}