[swift] Swift에서 디렉토리 생성 후 파일 이름 변경하기

Swift에서 파일을 생성하고 파일 이름을 변경해야 하는 경우가 종종 있습니다. 이번 글에서는 Swift에서 디렉토리를 생성한 후에 파일을 생성하고 파일 이름을 변경하는 방법에 대해 살펴보겠습니다.

1. 디렉토리 생성하기

먼저, 디렉토리를 생성해야 합니다. 아래의 코드는 FileManager를 사용하여 디렉토리를 생성하는 방법을 보여줍니다.

let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let newDirectoryURL = documentsDirectory.appendingPathComponent("MyNewDirectory")

do {
    try FileManager.default.createDirectory(at: newDirectoryURL, withIntermediateDirectories: true, attributes: nil)
} catch {
    print(error)
}

2. 파일 생성하기

이제 해당 디렉토리에 파일을 생성할 수 있습니다. 아래의 코드는 Data를 사용하여 파일을 생성하는 방법을 보여줍니다.

let newFileURL = newDirectoryURL.appendingPathComponent("myfile.txt")
let data = "Hello, World!".data(using: .utf8)

FileManager.default.createFile(atPath: newFileURL.path, contents: data, attributes: nil)

3. 파일 이름 변경하기

마지막으로, 파일 이름을 변경하는 방법을 살펴보겠습니다. 아래의 코드는 FileManager를 사용하여 파일 이름을 변경하는 방법을 보여줍니다.

let newFileName = newDirectoryURL.appendingPathComponent("newname.txt")

do {
    try FileManager.default.moveItem(at: newFileURL, to: newFileName)
} catch {
    print(error)
}

이제 Swift에서 디렉토리를 생성하고 파일 이름을 변경하는 방법에 대해 알아보았습니다. 위의 코드를 참고하여 원하는 기능을 구현해 보세요.

참고 자료