[swift] 외부 파일 시스템과의 상호 작용

이번에는 Swift에서 외부 파일 시스템과 상호 작용하는 방법을 알아보겠습니다.

파일 시스템 접근 권한 확인

Swift에서 외부 파일 시스템에 접근하려면 먼저 해당 파일 또는 디렉토리에 대한 권한을 확인해야 합니다. 이를 위해서는 FileManager 클래스의 fileExists 메서드를 사용하여 파일이나 디렉토리가 존재하는지 확인할 수 있습니다. 또는 isReadableFile(atPath:), isWritableFile(atPath:) 등의 메서드를 통해 읽기 및 쓰기 권한을 확인할 수 있습니다.

let fileManager = FileManager.default
let filePath = "/path/to/file"

if fileManager.fileExists(atPath: filePath) {
    if fileManager.isReadableFile(atPath: filePath) {
        print("Readable")
    }
    if fileManager.isWritableFile(atPath: filePath) {
        print("Writable")
    }
}

파일 및 디렉토리 작업

외부 파일 시스템과 상호 작용하기 위해 파일이나 디렉토리를 생성, 복사, 이동, 삭제하는 작업을 수행해야 할 때가 있습니다. 이러한 작업은 FileManager 클래스를 사용하여 간단하게 처리할 수 있습니다.

파일 생성

let filePath = "/path/to/newfile.txt"
let contents = "Hello, World!"

do {
    try contents.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)
} catch {
    print("Error: \(error)")
}

파일 복사

let sourcePath = "/path/to/sourcefile.txt"
let destinationPath = "/path/to/destination"

do {
    try fileManager.copyItem(atPath: sourcePath, toPath: destinationPath)
} catch {
    print("Error: \(error)")
}

파일 이동

let currentPath = "/path/to/currentfile.txt"
let newPath = "/path/to/newlocation"

do {
    try fileManager.moveItem(atPath: currentPath, toPath: newPath)
} catch {
    print("Error: \(error)")
}

파일 삭제

let filePath = "/path/to/filetodelete.txt"

do {
    try fileManager.removeItem(atPath: filePath)
} catch {
    print("Error: \(error)")
}

요약

Swift에서 외부 파일 시스템과 상호 작용하는 방법에 대해 간단히 살펴보았습니다. FileManager 클래스를 활용하여 파일과 디렉토리를 다루는 다양한 작업을 수행할 수 있습니다.

더 많은 정보는 Apple Developer Documentation에서 확인할 수 있습니다.