Qt拷貝檔案、資料夾以及拷貝進度
阿新 • • 發佈:2019-01-23
標頭檔案:
#ifndef SFILECOPY_H
#define SFILECOPY_H
#include <QObject>
#include <QDir>
class SFileCopy : public QObject
{
Q_OBJECT
public:
explicit SFileCopy(QObject *parent = 0);
~SFileCopy();
//拷貝檔案:
bool copyFileToPath(QString sourceDir ,QString toDir, bool coverFileIfExist);
//拷貝資料夾:
bool copyDirectoryFiles(const QString &fromDir, const QString &toDir, bool coverFileIfExist);
signals:
void sigCopyDirStation(float num);
void sigCopyDirOver();
private:
QDir * m_createfile = Q_NULLPTR;
float m_total = 0;
float m_value = 0;
bool m_firstRead = true;
};
#endif // SFILECOPY_H
原始檔:
#include "sfilecopy.h"
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QDebug>
SFileCopy::SFileCopy(QObject *parent) : QObject(parent)
{
m_createfile = new QDir();
}
SFileCopy::~SFileCopy()
{
if(m_createfile) {
m_createfile = Q_NULLPTR;
delete m_createfile;
}
}
bool SFileCopy::copyFileToPath(QString sourceDir, QString toDir, bool coverFileIfExist)
{
toDir.replace("\\","/");
if (sourceDir == toDir){
return true;
}
if (!QFile::exists(sourceDir)){
return false;
}
bool exist = m_createfile->exists(toDir);
if (exist){
if(coverFileIfExist){
m_createfile->remove(toDir);
}
}
if(!QFile::copy(sourceDir, toDir)) {
return false;
}
return true;
}
bool SFileCopy::copyDirectoryFiles(const QString &fromDir, const QString &toDir, bool coverFileIfExist)
{
QDir sourceDir(fromDir);
QDir targetDir(toDir);
qDebug() << "copyDirectoryFiles:" << fromDir << toDir;
if(!targetDir.exists()){ /**< 如果目標目錄不存在,則進行建立 */
if(!targetDir.mkdir(targetDir.absolutePath())) {
return false;
}
}
QFileInfoList fileInfoList = sourceDir.entryInfoList();
if(m_firstRead) {
int isfileTMP = 0;
qDebug() << "a copyDirectoryFiles:" << fileInfoList.count();
foreach(QFileInfo fileInfo, fileInfoList){
if(fileInfo.isFile()) {
isfileTMP++;
}
}
m_total = fileInfoList.count() - 2 - isfileTMP; // 2為.和..
m_value = 0;
m_firstRead = false;
qDebug() << "a copyDirectoryFiles:" << fileInfoList.count() <<m_total << isfileTMP;
emit sigCopyDirStation(m_value/m_total);
if(m_value == m_total) {
m_firstRead = true;
emit sigCopyDirStation(1);
emit sigCopyDirOver();
}
} else {
m_value++;
qDebug() << "a copyDirectoryFiles:" << m_value <<m_total;
emit sigCopyDirStation(m_value/m_total);
if((m_value/m_total == 1) || (m_value > m_total) || (m_value == m_total)) {
m_firstRead = true;
emit sigCopyDirOver();
}
}
foreach(QFileInfo fileInfo, fileInfoList){
if(fileInfo.fileName() == "." || fileInfo.fileName() == "..") {
continue;
}
if(fileInfo.isDir()){ /**< 當為目錄時,遞迴的進行copy */
if(!copyDirectoryFiles(fileInfo.filePath(), targetDir.filePath(fileInfo.fileName()), coverFileIfExist)) {
return false;
}
} else{ /**< 當允許覆蓋操作時,將舊檔案進行刪除操作 */
if(coverFileIfExist && targetDir.exists(fileInfo.fileName())){
targetDir.remove(fileInfo.fileName());
}
/// 進行檔案copy
if(!QFile::copy(fileInfo.filePath(), targetDir.filePath(fileInfo.fileName()))){
return false;
}
}
}
return true;
}