[swift] Swift으로 디렉토리 생성 후 파일을 다른 위치로 이동하기
Swift을 사용하여 디렉토리를 생성하고 파일을 다른 위치로 이동하는 방법을 알아보겠습니다.
디렉토리 생성하기
import Foundation
let fileManager = FileManager.default
let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
let newFolderURL = documentsDirectory.appendingPathComponent("NewFolder")
do {
try fileManager.createDirectory(at: newFolderURL, withIntermediateDirectories: true, attributes: nil)
print("디렉토리가 생성되었습니다: \(newFolderURL.path)")
} catch {
print("디렉토리 생성에 실패했습니다: \(error)")
}
위 코드는 FileManager
를 사용하여 앱의 문서 디렉토리에 “NewFolder”라는 이름의 새 디렉토리를 생성하는 예제입니다.
파일 이동하기
let sourceURL = URL(fileURLWithPath: "path_to_source_file")
let destinationURL = newFolderURL.appendingPathComponent("file.txt")
do {
try fileManager.moveItem(at: sourceURL, to: destinationURL)
print("파일을 이동했습니다: \(destinationURL.path)")
} catch {
print("파일 이동에 실패했습니다: \(error)")
}
moveItem
메서드를 사용하여 파일을 다른 위치로 이동할 수 있습니다. 이때, sourceURL
은 원본 파일의 경로이고, destinationURL
은 파일을 이동할 목적지 경로입니다.
위와 같이 Swift을 사용하여 디렉토리를 생성하고 파일을 다른 위치로 이동할 수 있습니다.
이러한 파일 및 디렉토리 조작 기능은 Foundation
프레임워크의 FileManager
클래스를 통해 제공됩니다.
더 많은 정보는 Apple 개발자 문서를 참고하시기 바랍니다.