zip7z.h
#ifndef ZIP7Z_H
#define ZIP7Z_H
#include <QObject>
#include <QDir>
#include <QProcess>
#include <QApplication>
class Zip7z : public QObject
{
Q_OBJECT
public:
static bool Zip(QString dest, QString src_partten, QString &out);
static bool UnZip(QString src, QString dest, QString &out);
private:
static bool Init(QString &out);
};
#endif // ZIP7Z_H
Zip7z.cpp
#include "zip7z.h"
bool Zip7z::Zip(QString dest, QString src_partten, QString &out) {
QString filestate = "";
out = "";
if (Init(filestate) == false) {
out = filestate + QString::fromLocal8Bit("不能执行压缩");
return false;
}
else {
QProcess p(0);
QStringList args = QStringList();
args.append("a");
args.append(dest);
args.append(src_partten);
p.start(QApplication::applicationDirPath() + "/7za.exe", args);
p.waitForStarted();
p.waitForFinished();
out = QString::fromLocal8Bit(p.readAllStandardOutput());
return true;
}
}
bool Zip7z::UnZip(QString src, QString dest, QString &out) {
QString filestate = "";
out = "";
if (Init(filestate) == false) {
out = filestate + QString::fromLocal8Bit("不能执行压缩");
return false;
}
else {
QProcess p(0);
QStringList args = QStringList();
args.append("x");
args.append(src);
args.append("-o" + dest);//-o和目标目录必须连在一起
args.append("-aoa");//不提示,直接覆盖同名文件
p.start(QApplication::applicationDirPath() + "/7za.exe", args);
p.waitForStarted();
p.waitForFinished();
out = QString::fromLocal8Bit(p.readAllStandardOutput());
return true;
}
}
bool Zip7z::Init(QString &out) {
out = "";
QStringList depends = QStringList();
depends.append("7za.exe");
depends.append("7za.dll");
for (QString file : depends) {
QString loaclfile = QApplication::applicationDirPath() + "/" + file;
if (QDir().exists(file) == false) {
//从资源释放文件到本地
QString qrcfile = ":/7z/" + file;
QFile::copy(qrcfile, loaclfile);
}
}
out = QString::fromLocal8Bit("文件检查完成,正常.");
return true;
}
压缩和解压调用
void DownLoadFiles::unzip(QString curDownfile)
{
QString out;
// bool successful = Zip7z::Zip(QApplication::applicationDirPath() + "/123.zip",
// QApplication::applicationDirPath() + "/789.txt", out);
// if (!successful) {
// QApplication::beep();
// }
// qDebug() << out;
// qDebug() << "--------------------------------------------------------";
QString path = curDownfile.mid(0, curDownfile.size() - 4);
Zip7z::UnZip(QApplication::applicationDirPath() + QString("/%1").arg(curDownfile),
QApplication::applicationDirPath() + QString("/%1").arg(path), out);
qDebug() << out;
}