美文网首页
Swift:文件操作

Swift:文件操作

作者: 阿里懒 | 来源:发表于2016-09-07 20:38 被阅读0次

    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:文件操作

          本文链接:https://www.haomeiwen.com/subject/ehtsettx.html