使用quazip在内存中压缩

quazip是一个QT下实现的压缩和解压库

下载地址:

https://github.com/stachenov/quazip/releases

quazip已经是带了内存中解压和压缩的功能,但是没有封装到JlCompress

在编译quazip时需要JlCompress类中的static bool compressFile(QuaZip* zip, QString fileName, QString fileDest);等几个private函数修改为protected,因为我是继承了JlCompress类,需要使用bool compressFile(QuaZip* zip, QString fileName, QString fileDest);函数。

下面是我实现的JlCompressEx类,只做了将文件压缩到内存中

头文件内容

#pragma once


#include "quazip/JlCompress.h"
#include "quazip/quazip.h"

#include 
#include 

class JlCompressEx : public JlCompress
{
public:
	// 文件压缩到内存buffer,zipIoDevice可以使用QBuffer zipBuffer;
	static bool CompressToBuffer(QString file, QIODevice& zipIoDevice);
	// 内存数据压缩到内存buffer
	static bool CompressToBuffer(QByteArray& sourceData, QString fileName, QIODevice& zipIoDevice);
	// 文件压缩到内存buffer
	static bool CompressToBuffer(QStringList files, QIODevice& zipIoDevice);

public:
	// 压缩数据
	static bool CompressBuffer(QuaZip& zip, QByteArray& sourceData, QString fileName);
};

cpp文件内容 

#include "JlCompressEx.h"


bool JlCompressEx::CompressToBuffer(QString file, QIODevice& zipIoDevice)
{
	QuaZip zip(&zipIoDevice);
	//QDir().mkpath(QFileInfo(fileCompressed).absolutePath());
	if (!zip.open(QuaZip::mdCreate))
	{
		return false;
	}
	// 
	if (!compressFile(&zip, file, QFileInfo(file).fileName())) {
		return false;
	}

	// 
	zip.close();
	if (zip.getZipError() != UNZ_OK) {
		return false;
	}

	return true;
}

bool JlCompressEx::CompressToBuffer(QByteArray& sourceData, QString fileName, QIODevice& zipIoDevice)
{
	QuaZip zip(&zipIoDevice);
	//QDir().mkpath(QFileInfo(fileCompressed).absolutePath());
	if (!zip.open(QuaZip::mdCreate))
	{
		return false;
	}

	if (!CompressBuffer(zip, sourceData, fileName))
	{
		return false;
	}

	// 
	zip.close();
	if (zip.getZipError() != UNZ_OK) {
		return false;
	}

	return true;
}

bool JlCompressEx::CompressToBuffer(QStringList files, QIODevice& zipIoDevice)
{
	// 
	QuaZip zip(&zipIoDevice);
	//QDir().mkpath(QFileInfo(fileCompressed).absolutePath());
	if (!zip.open(QuaZip::mdCreate))
	{
		return false;
	}

	// 
	QFileInfo info;
	for (int index = 0; index < files.size(); ++index) {
		const QString & file(files.at(index));
		info.setFile(file);
		if (!info.exists() || !compressFile(&zip, file, info.fileName())) {
			return false;
		}
	}

	// 
	zip.close();
	if (zip.getZipError() != 0)
	{
		return false;
	}

	return true;
}

bool JlCompressEx::CompressBuffer(QuaZip& zip, QByteArray& sourceData, QString fileName)
{
	// 
	if (zip.getMode() != QuaZip::mdCreate &&
		zip.getMode() != QuaZip::mdAppend &&
		zip.getMode() != QuaZip::mdAdd)
	{
		return false;
	}
	// 
	QuaZipFile outFile(&zip);
	if (!outFile.open(QIODevice::WriteOnly, QuaZipNewInfo(fileName)))
	{
		return false;
	}
	// 
	if (outFile.write(sourceData) != sourceData.size())
	{
		return false;
	}
	if (outFile.getZipError() != UNZ_OK)
	{
		return false;
	}

	// 
	outFile.close();
	if (outFile.getZipError() != UNZ_OK)
	{
		return false;
	}

	return true;
}

 

你可能感兴趣的:(使用quazip在内存中压缩)