[swift] Swift로 파일 이동 시 대상 경로가 이미 존재하는 경우 처리 방법
파일을 이동하는 동안 대상 경로에 이미 파일이 존재하는 경우가 발생할 수 있습니다. 이 상황에 대처하기 위해 Swift에서는 몇 가지 방법을 제공합니다.
1. 파일 덮어쓰기
새로 이동할 파일을 기존 파일이 있는 경로에 덮어쓰기 하는 방법이 있습니다. 이는 FileManager
의 copyItem
메서드를 사용하여 새 파일로 대상 경로에 덮어쓸 수 있습니다.
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)
} catch {
print(error)
}
2. 파일명 변경
다른 방법으로는 대상 경로에 이미 파일이 존재하는 경우, 새 파일의 이름을 변경하여 충돌을 피할 수 있습니다.
let fileManager = FileManager.default
let sourceURL = URL(fileURLWithPath: "path_to_source_file")
let destinationURL = URL(fileURLWithPath: "path_to_destination_file")
do {
if fileManager.fileExists(atPath: destinationURL.path) {
let fileName = sourceURL.deletingPathExtension().lastPathComponent
let fileExtension = sourceURL.pathExtension
let newFileName = "\(fileName)_new" // 변경되지 않은 파일명에 '_new'를 추가
let newDestinationURL = destinationURL.deletingLastPathComponent().appendingPathComponent("\(newFileName).\(fileExtension)")
try fileManager.copyItem(at: sourceURL, to: newDestinationURL)
} else {
try fileManager.copyItem(at: sourceURL, to: destinationURL)
}
} catch {
print(error)
}
파일을 이동하거나 복사하는 과정에서 대상 경로에 이미 파일이 있는 상황을 처리하는 방법은 위와 같습니다. 선택된 방법에 따라 충돌이나 대상 경로 파일의 상태에 대한 추가적인 처리가 필요할 수 있습니다.
이러한 방법으로 파일 이동 시 대상 경로에 이미 파일이 존재하는 경우에 대처할 수 있습니다.
Swift FileManager 공식 문서에서 더 많은 정보를 확인할 수 있습니다.