[swift] 파일 복사 및 이동

파일 복사

파일을 복사하려면 FileManager를 사용하여 소스 파일을 읽고 대상 경로에 파일을 쓰면 됩니다. 아래는 파일을 복사하는 예제 코드입니다.

import Foundation

let fileManager = FileManager.default
let sourceURL = URL(fileURLWithPath: "path/to/source/file")
let destinationURL = URL(fileURLWithPath: "path/to/destination/file")

do {
    try fileManager.copyItem(at: sourceURL, to: destinationURL)
    print("파일이 복사되었습니다.")
} catch {
    print("파일 복사 중 오류가 발생했습니다: \(error)")
}

파일 이동

파일을 이동할 때도 FileManager를 사용하여 파일을 이동하고, 원래의 파일을 삭제할 수 있습니다.

import Foundation

let fileManager = FileManager.default
let sourceURL = URL(fileURLWithPath: "path/to/source/file")
let destinationURL = URL(fileURLWithPath: "path/to/destination/file")

do {
    try fileManager.moveItem(at: sourceURL, to: destinationURL)
    print("파일이 이동되었습니다.")
} catch {
    print("파일 이동 중 오류가 발생했습니다: \(error)")
}

위의 코드에서 path/to/source/file은 복사 또는 이동할 원본 파일의 경로를 나타내며, path/to/destination/file은 대상 파일의 경로를 나타냅니다.

이제 파일을 손쉽게 복사하고 이동할 수 있습니다!