Swift:文件操作

1.获取文件/文件夹大小

//文件管理者
static let mFileManager = NSFileManager.defaultManager()
static func getFileSize(filePath:String)->Int{
    var totalSize:Int = 0
    //判断字符串是否为文件/文件夹
    var isDir: ObjCBool = ObjCBool(false)
    let exists:Bool = mFileManager.fileExistsAtPath(filePath, isDirectory: &isDir)
    
    if exists {
        if isDir {
            let subFileNames:NSArray = mFileManager.subpathsAtPath(filePath)!
            for subFileName in subFileNames {
                let subFilePath = (filePath as NSString).stringByAppendingPathComponent(subFileName as! String)
                totalSize += getFileSize(subFilePath)
            }
        }else{
            let attr:NSDictionary = try! mFileManager.attributesOfItemAtPath(filePath)
            let size = attr["NSFileSize"] as! Int
            totalSize += size
            
        }
    }else{
        return 0
    }
    return totalSize
}

//扩展Double转化为String保留多少位
extension Double {
    func format(f: String) -> String {
        return String(format: "%\(f)f", self)
    }
}

//转化为显示字符串
static func getSizeStr(fileSize:Int) -> String{
    if fileSize == 0 {
        return ""
    }
    if fileSize > 1024 * 1024 {
        return "\((Double(fileSize)/(1024*1024)).format(".2"))MB"
    }else if fileSize > 1024{
        return "\(fileSize/1024)KB"
    }
    return "\(fileSize)B"
}

你可能感兴趣的:(Swift:文件操作)