오늘은 FileManager에 대해서 알아보겠습니다.
가끔 사용할 일이 생기는데 자주 사용하지 않다보니까 사용할 때 마다 구글링하게 되서 이참에 확실히 정리해보려고 합니다.
애플의 macOS 및 iOS 운영 체제에서 파일 시스템과 상호작용하기 위해 사용됩니다. 주로 Foundation 프레임워크의 일부로 제공되며, 파일 및 디렉터리의 생성, 복사, 이동, 삭제, 속성 조회 등의 작업을 수행할 수 있습니다.
FileManager.default 로 파일 작업을 수행할 수 있습니다. class FileManager : NSObject {
class var `default`: FileManager
}
createFile(atPath:contents:attributes:)
createDirectory(at:withIntermediateDirectories:attributes:)
아래 메서드를 사용하여 파일이나 디렉터리가 특정 경로에 존재하는지 확인할 수 있습니다.
fileExists(atPath:)
attributesOfItem는 파일의 크기, 생성일, 수정일 등 다양한 속성을 조회할 수 있습니다. setAttributes를 통해 속성을 변경할 수 있습니다. attributesOfItem(atPath:)
setAttributes(_:ofItemAtPath:)
contents(atPath:)
contentsOfDirectory(at:includingPropertiesForKeys:options:)
지정된 경로의 파일이나 디렉터리를 삭제합니다.
removeItem(at:)
do {
try FileManager.default.removeItem(atPath: "/path/to/file.txt")
print("File deleted")
} catch {
print("Error deleting file: \(error)")
}
copyItem(at:to:)
do {
try FileManager.default.copyItem(atPath: "/path/to/source.txt", toPath: "/path/to/destination.txt")
print("File copied")
} catch {
print("Error copying file: \(error)")
}
moveItem(at:to:)
do {
try FileManager.default.moveItem(atPath: "/path/to/source.txt", toPath: "/path/to/newLocation.txt")
print("File moved")
} catch {
print("Error moving file: \(error)")
}
contentsOfDirectory(at:includingPropertiesForKeys:options:)
let directoryURL = URL(fileURLWithPath: "/path/to/directory")
do {
let files = try FileManager.default.contentsOfDirectory(at: directoryURL, includingPropertiesForKeys: nil, options: [])
for file in files {
print(file.lastPathComponent)
}
} catch {
print("Error reading directory contents: \(error)")
}