[swift] Swift에서 파일의 크기 확인하는 방법

Swift에서 파일의 크기를 확인하려면 FileManager 클래스를 사용해야 합니다. 아래 예제에서는 파일의 경로를 인자로 받아 해당 파일의 크기를 반환하는 함수를 작성해보겠습니다.

import Foundation

func getFileSize(atPath path: String) -> UInt64? {
    let fileManager = FileManager.default
    do {
        let fileInfo = try fileManager.attributesOfItem(atPath: path)
        if let fileSize = fileInfo[FileAttributeKey.size] as? UInt64 {
            return fileSize
        }
    } catch {
        print("Error: \(error)")
    }
    return nil
}

위의 예제에서 getFileSize 함수는 경로를 입력받아 해당 경로에 있는 파일의 크기를 UInt64형태로 반환합니다. FileManager 클래스의 attributesOfItem 메소드를 사용하여 파일의 속성을 가져온 후, 속성 중 size 키에 해당하는 값을 추출합니다. 만약 파일의 크기를 가져올 수 없는 경우, nil을 반환합니다.

이제 이 함수를 사용하여 파일의 크기를 확인해봅시다.

let filePath = "/Users/username/Documents/sample.txt"
if let fileSize = getFileSize(atPath: filePath) {
    let fileSizeInKB = fileSize / 1024
    print("파일의 크기는 \(fileSizeInKB) KB입니다.")
} else {
    print("파일의 크기를 가져올 수 없습니다.")
}

위의 예제에서는 “/Users/username/Documents/sample.txt” 경로에 있는 파일의 크기를 가져와 출력합니다. getFileSize 함수를 통해 파일의 크기를 받아와 fileSizeInKB 변수에 저장한 후, 출력합니다.

참고 자료: