[Swift] FileManager

어흥·2024년 8월 5일

Computer Science

목록 보기
25/28

오늘은 FileManager에 대해서 알아보겠습니다.
가끔 사용할 일이 생기는데 자주 사용하지 않다보니까 사용할 때 마다 구글링하게 되서 이참에 확실히 정리해보려고 합니다.

FileManager

애플의 macOS 및 iOS 운영 체제에서 파일 시스템과 상호작용하기 위해 사용됩니다. 주로 Foundation 프레임워크의 일부로 제공되며, 파일 및 디렉터리의 생성, 복사, 이동, 삭제, 속성 조회 등의 작업을 수행할 수 있습니다.

  • FileManager는 싱글톤 패턴으로 설계되어 있어 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)")
}

0개의 댓글