[swift] Swift로 파일 이동 시 경로에 해당하는 폴더가 없을 경우 처리 방법
먼저 fileManager의 isReadableFile(atPath:) 메서드를 사용하여 이동할 파일이 존재하는지 확인합니다. 그런 다음 새 경로에 해당하는 폴더가 있는지를 확인하고, 없을 경우 createDirectory(atPath:withIntermediateDirectories:attributes:) 메서드로 새로운 폴더를 생성할 수 있습니다.
아래 예시는 Swift로 파일 이동 시 경로에 해당하는 폴더가 없는 경우를 처리하는 방법을 보여줍니다.
import Foundation
let fileManager = FileManager.default
let currentPath = "path/to/current/folder/file.txt"
let newPath = "path/to/new/folder/file.txt"
if fileManager.isReadableFile(atPath: currentPath) {
let newFolderPath = (newPath as NSString).deletingLastPathComponent
var isDirectory: ObjCBool = false
if !fileManager.fileExists(atPath: newFolderPath, isDirectory: &isDirectory) || !isDirectory.boolValue {
do {
try fileManager.createDirectory(atPath: newFolderPath, withIntermediateDirectories: true, attributes: nil)
} catch {
// Handle directory creation error
print("Error creating directory: \(error)")
}
}
do {
try fileManager.moveItem(atPath: currentPath, toPath: newPath)
print("File moved successfully")
} catch {
// Handle file move error
print("Error moving file: \(error)")
}
} else {
// Handle file does not exist or is not readable
print("File does not exist or is not readable at the current path")
}
위의 예시 코드에서는 먼저 현재 경로에 파일이 존재하는지 확인하고, 새 경로에 해당하는 폴더가 없는 경우 폴더를 생성하고 파일을 이동합니다. 에러가 발생할 경우 에러를 처리하는 방법도 함께 포함되어 있습니다.
참고문헌:
- Apple Developer Documentation. “FileManager”. Apple Inc. https://developer.apple.com/documentation/foundation/filemanager