ios .创建文件,文件夹,压缩文件

文件压缩使用的是GZIP swift版本:GZIP

这个只提供了一个data的扩展,所以要自己创建文件,当然没有直接的三方工具方便,不过可行哦~

class DataTrackingCache: NSObject {
    
    static let directory = "DataTracking"
    static let gzipDiretory = "DataTrackingZIP"
    static let shared = DataTrackingCache()
    
    lazy var tempDirectory: String = {
        let tempPath = NSTemporaryDirectory()
        return tempPath
    }()
    
    // 判断文件是否存在
    class func judgeFileIsExist(_ filePath: String) -> Bool {
        return FileManager.default.fileExists(atPath: filePath)
    }
    
    // 创建文件
    func creatText(_ filePath: String, contents: Data? = Data()) {
        if !FileManager.default.fileExists(atPath: filePath) {
            FileManager.default.createFile(atPath: filePath, contents: contents, attributes: nil)
        }
    }
    
    // 创建文件夹
    func creatFile(_ filePath: String, isDirectories: Bool = false) {
        if !FileManager.default.fileExists(atPath: filePath) {
            try? FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: isDirectories, attributes: nil)
        }
    }
    // 删除文件
    class func deleteFile(_ filePath: String) {
        if FileManager.default.fileExists(atPath: filePath) {
            do {
                try FileManager.default.removeItem(atPath: filePath)
            } catch {
                debugPrint("\(error)")
            }
        }
    }
    
    var getNowTimeTimestamp: String {
        let datenow = Date()
        let timeSp = String(format: "%ld", Int(datenow.timeIntervalSince1970 * 1000))
        return timeSp
    }
    
    lazy var storagePath: String = {
        var path = (NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first ?? "") + "/" + DataTrackingCache.directory
        creatFile(path)
        path += "/" + String(format: "%@.txt", getNowTimeTimestamp)
        creatText(path)
        return path
    }()
    
    var zipPath: String {
        var path = (NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first ?? "") + "/" + DataTrackingCache.directory
        path += "/" + String(format: "%@.gz", getNowTimeTimestamp)
        creatText(path)
        return path
    }
    
    static func write(withData data: Any) {
        
        let fileHandle = FileHandle(forUpdatingAtPath: DataTrackingCache.shared.storagePath)
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)
            let json = String(data: jsonData, encoding: .utf8) ?? ""
            let jsonString = json + ",\n"
            fileHandle?.seekToEndOfFile()
            let strData = jsonString.data(using: .utf8) ?? Data()
            fileHandle?.write(strData)
            fileHandle?.closeFile()
            readFile()
        }
        catch {
            debugPrint(" error\(error.localizedDescription)")
        }
    }
    
    static func readFile() {
        
        let path = DataTrackingCache.shared.storagePath
        let strData = FileHandle.init(forReadingAtPath: path)?.availableData
        do {
            if let strData = strData {
                let compressedData: Data = try strData.gzipped()
                let optimizedData: Data = try strData.gzipped(level: .bestCompression)
                DataTrackingCache.shared.creatText(path + ".gz", contents: compressedData)
            }
        }
        catch {
        }
    }
    
    // 计算文件大小
    class func getFileSizeWithFileName(_ path: String) -> UInt64 {
        // 1.文件总大小
        var totalSize: UInt64 = 0
        // 2.创建文件管理者
        let fileManager = FileManager.default
        // 3.判断文件存不存在以及是否是文件夹
        var isDirectory: ObjCBool = ObjCBool(false)
        let isFileExist = fileManager.fileExists(atPath: path, isDirectory: &isDirectory)
        if !isFileExist {
            return totalSize
        } // 文件不存在
        if (isDirectory).boolValue { // 是文件夹
            guard let subPaths = fileManager.subpaths(atPath: path)  else {
                return totalSize
            }
            for subPath in subPaths {
                let filePath = path.appendingFormat("/%@", subPath)
                var isDirectory: ObjCBool = ObjCBool(false)
                let isExistFile = fileManager.fileExists(atPath: filePath, isDirectory: &isDirectory)
                if !isDirectory.boolValue && isExistFile && !filePath.contains("DS") {
                    do {
                        if let attr: NSDictionary = try fileManager.attributesOfItem(atPath: path) as NSDictionary? {
                            totalSize += attr.fileSize()
                        }
                    } catch {
                        debugPrint("Error: \(error)")
                    }
                }
            }
        } else { // 不是文件夹
            do {
                if let attr: NSDictionary = try fileManager.attributesOfItem(atPath: path) as NSDictionary? {
                    totalSize += attr.fileSize()
                }
            } catch {
                debugPrint("Error: \(error)")
            }
        }
        
        return totalSize
    }
    
    // MARK: ...获取文件的大小
    class func fileSize(_ filePath: String) -> Int64 {
        if !self.judgeFileIsExist(filePath) {
            return 0
        }
        do {
            let fileInfo = try FileManager.default.attributesOfItem(atPath: filePath)
            guard let size = fileInfo[FileAttributeKey.size] as? Int64 else { return 0}
            return size
        } catch {
            
        }
        return 0
    }
}

在其他需要掉用的地方,调用write方法,就可以存储文件里面了,我是为了看压缩效果,直接write后直接read了,应该在需要read的地方再read,read时才压缩,压缩后上传,上传无论成功与否都应该删掉压缩文件,成功是删掉原文件

总结的不好,先放在这里,实现还未完成:压缩了以后应该放在另外一个文件夹,还没有放,细节处理不到位,先记录过程,后面再更新~

 

你可能感兴趣的:(iOS,Swift)