[swift] Swift으로 디렉토리 생성 후 파일을 읽고 쓰기

Swift은 Apple의 주니어 프로그래머들에게 인기 있는 프로그래밍 언어입니다. 이 언어를 사용하여 파일 시스템에서 디렉토리를 생성하고 파일을 읽고 쓰는 방법을 살펴보겠습니다.

디렉토리 생성

디렉토리를 생성하려면 FileManager를 사용해야 합니다. 이 클래스의 createDirectory 메서드를 사용하여 새로운 디렉토리를 생성할 수 있습니다. 아래는 Swift에서 디렉토리를 생성하는 예제 코드입니다.

import Foundation

let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let newFolderURL = documentsURL.appendingPathComponent("NewFolder")

do {
    try fileManager.createDirectory(atPath: newFolderURL.path, withIntermediateDirectories: true, attributes: nil)
} catch {
    print("Error creating directory: \(error)")
}

위 코드에서는 FileManagercreateDirectory 메서드를 사용하여 새로운 디렉토리를 생성하였습니다.

파일 읽고 쓰기

파일을 읽고 쓰려면 FileHandle 또는 Data를 사용할 수 있습니다. 아래는 파일을 생성하고 데이터를 쓰는 예제 코드입니다.

let fileURL = newFolderURL.appendingPathComponent("example.txt")
let data = "Hello, world!".data(using: .utf8)

fileManager.createFile(atPath: fileURL.path, contents: data, attributes: nil)

do {
    let fileHandle = try FileHandle(forWritingTo: fileURL)
    fileHandle.write(data!)
    fileHandle.closeFile()
} catch {
    print("Error writing to file: \(error)")
}

위 코드에서는 먼저 파일을 생성하고 데이터를 씁니다. 그 후 FileHandle을 사용하여 파일을 열고 데이터를 씁니다.

이제 Swift으로 디렉토리를 생성하고 파일을 읽고 쓰는 방법에 대해 알아보았습니다. 이러한 기능을 사용하여 파일 시스템을 조작할 수 있습니다.

참고 자료: Apple Developer Documentation, Swift.org