zoukankan      html  css  js  c++  java
  • Qt 文件常见操作管理类

    这里将 Qt 常用的文件操作函数封装成一个单例类,方便复用。


    一、类定义

    FileMgr.h:

    #ifndef FILEMGR_H
    #define FILEMGR_H
    
    // Qt文件管理类
    #include <QFile>
    #include <QFileInfo>
    #include <QDir>
    #include <QCryptographicHash>
    #include <QDebug>
    
    class FileMgr
    {
    public:
        static FileMgr& GetInstance() {
            static FileMgr m_fileMgr;
            return m_fileMgr;
        }
    
        bool isFileExist(const QString &sFilePath); // 文件是否存在
        bool createDir(QString sDirPath); // 创建文件夹
        bool copyFile(const QString &sSrcFile, const QString &sDestFile, const bool &bCover); // 复制文件
        bool moveFile(const QString &sSrcFile, const QString &sDestFile, const bool &bCover); // 移动文件
        bool copyDir(const QString &sSrcDir, const QString &sDestDir, const bool &bCover); // 复制文件夹
        bool delFileOrDir(const QString &sPath); // 删除文件或文件夹
        QByteArray getFileMd5(const QString &sFilePath); // 计算获取文件的MD5值
    
    private:
        FileMgr();
    };
    
    #endif // FILEMGR_H
    

    二、类实现

    2.1 文件是否存在

    // 文件是否存在
    bool FileMgr::isFileExist(const QString &sFilePath)
    {
        // 是否传入了空的路径
        if (sFilePath.isEmpty())
            return false;
    
        return QFile().exists(sFilePath);
    }
    

    很简单,本质就一句QFile().exists(sFilePath)就可以搞定,感觉这里封装都有点多余。


    2.2 创建文件夹

    // 创建文件夹
    bool FileMgr::createDir(QString sDirPath)
    {
        QStringList dirNameArray = sDirPath.split('/');
        int nameSize = dirNameArray.size();
        for(int i=1; i<nameSize+1; i++)
        {
            QString iBefAllDirStr = "";
            for(int j=0; j<i; j++)
            {
                iBefAllDirStr += QString(dirNameArray.at(j) + '/');
            }
    
            QDir diri(iBefAllDirStr);
            if(diri.exists() == false) {
                diri.mkdir(iBefAllDirStr);
            }
        }
    
        return true;
    }
    

    这里使用了递归来创建多级目录的文件夹。


    2.3 复制、移动文件

    // 复制文件
    bool FileMgr::copyFile(const QString &sSrcFile, const QString &sDestFile, const bool &bCover)
    {
        // 是否传入了空的路径||源文件是否存在
        if (sSrcFile.isEmpty() || sDestFile.isEmpty() || !QFile().exists(sSrcFile))
            return false;
        // 源文件路径与目标路径相同
        if(sSrcFile == sDestFile)
            return true;
    
        // 判断目标文件的目录存不存在,不存在则创建
        QFileInfo fileInfo(sDestFile);
        QString sDirPath = fileInfo.absolutePath(); // 取目标文件所在的绝对目录路径
        if(!QDir().exists(sDirPath))
            createDir(sDirPath);
    
        // 如果文件存在,允许覆盖,则删除目标路径文件
        QFile sTempFile(sDestFile);
        if(sTempFile.exists()) {
            if(bCover)
                sTempFile.remove();
        }
    
        // 复制文件
        QFile file(sSrcFile);
        return file.copy(sDestFile);
    }
    
    // 移动文件
    bool FileMgr::moveFile(const QString &sSrcFile, const QString &sDestFile, const bool &bCover)
    {
        // 是否传入了空的路径||源文件是否存在
        if (sSrcFile.isEmpty() || sDestFile.isEmpty() || !QFile().exists(sSrcFile))
            return false;
        // 源文件路径与目标路径相同
        if(sSrcFile == sDestFile)
            return true;
    
        // 允许覆盖,如果文件存在,则删除目标路径文件
        if(bCover) {
            QFile file(sDestFile);
            if(file.exists()) {
                if(!file.remove()) // 删除失败则返回false
                    return  false;
            }
        }
    
        // 判断目标文件的目录存不存在,不存在则创建
        QFileInfo fileInfo(sDestFile);
        QString sDirPath = fileInfo.absolutePath(); // 取目标文件所在的绝对目录路径
        if(!QDir().exists(sDirPath))
            createDir(sDirPath);
    
        // 如果文件存在,允许覆盖,则删除目标路径文件
        QFile sTempFile(sDestFile);
        if(sTempFile.exists()) {
            if(bCover)
                sTempFile.remove();
        }
    
        // 移动文件
        QFile file(sSrcFile);
        return file.rename(sDestFile);
    }
    

    这两个函数实现很类似,所以放在一起讲。注意参数bCover,如果为 true,则将以覆盖的方式复制、移动文件,即若目标文件存在,则会先删除后复制、移动。


    2.4 复制文件夹

    // 复制文件夹
    bool FileMgr::copyDir(const QString &sSrcDir, const QString &sDestDir, const bool &bCover)
    {
        // 是否传入了空的路径||源文件夹是否存在
        if (sSrcDir.isEmpty() || sDestDir.isEmpty() || !QDir().exists(sSrcDir))
            return false;
    
        QDir sourceDir(sSrcDir);
        QDir destDir(sDestDir);
    
        // 如果目标目录不存在,则进行创建
        if(!destDir.exists()) {
            if(!(createDir(destDir.absolutePath())))
                return false;
        }
    
        QFileInfoList fileInfoList = sourceDir.entryInfoList();
        foreach(QFileInfo fileInfo, fileInfoList) {
            if(fileInfo.fileName() == "." || fileInfo.fileName() == "..")
                continue;
    
            // 当为目录时,递归的进行copy
            if(fileInfo.isDir()) {
                if(!copyDir(fileInfo.filePath(),
                    destDir.filePath(fileInfo.fileName()),
                    bCover))
                    return false;
            }
            else { // 当允许覆盖操作时,将旧文件进行删除操作
                if(bCover && destDir.exists(fileInfo.fileName())){
                    destDir.remove(fileInfo.fileName());
                 }
    
                // 进行文件copy
                if(!QFile::copy(fileInfo.filePath(),
                    destDir.filePath(fileInfo.fileName()))){
                        return false;
                }
            }
        }
    
        return true;
    }
    

    2.5 删除文件或文件夹

    // 删除文件或文件夹
    bool FileMgr::delFileOrDir(const QString &sPath) {
        //是否传入了空的路径||路径是否存在
        if (sPath.isEmpty() || !QDir().exists(sPath))
            return false;
    
        QFileInfo FileInfo(sPath);
        if (FileInfo.isFile()) // 如果是文件
            return QFile::remove(sPath);
        else if (FileInfo.isDir()) // 如果是文件夹
        {
            QDir qDir(sPath);
            return qDir.removeRecursively();
        }
    
        return true;
    }
    

    网上很多关于删除文件夹都用递归删除的方法,因为非空文件夹不能直接删除。其实 Qt 中有可以直接删除文件夹的函数QDir::removeRecursively(),从 Qt 5.0 开始引用的。


    2.6 获取文件的MD5值

    // 计算获取文件的MD5值
    QByteArray FileMgr::getFileMd5(const QString &sFilePath)
    {
        // 是否传入了空的路径||文件是否存在
        if (sFilePath.isEmpty() || !QFile().exists(sFilePath))
            return "";
    
        // 获取文件MD5值
        QFile md5File(sFilePath);
        md5File.open(QIODevice::ReadOnly);
        QByteArray ba = QCryptographicHash::hash(md5File.readAll(), QCryptographicHash::Md5);
        md5File.close();
        return ba.toHex();
    }
    

    QCryptographicHash类提供了生成密码散列的方法。该类可以用于生成二进制或文本数据的加密散列值。目前支持 MD4、MD5、SHA-1、SHA-224、SHA-256、SHA-384 和 SHA-512。这个类在 QtCore4.3 中被引入。更多相关文件操作请查看 Qt 帮助文档。

    这里提供一个文件 MD5 的验证网站:文件md5在线计算


    三、应用代码

    #include <QApplication>
    #include "FileMgr.h"
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
    
        // 文件是否存在
        qDebug() << FileMgr::GetInstance().isFileExist("./test.json");
        // 复制文件
        qDebug() << FileMgr::GetInstance().copyFile("./test.json", "./Dir/Dir2/test.json", true);
        // 移动文件
        qDebug() << FileMgr::GetInstance().moveFile("./test2.json", "./Dir/Dir2/test2.json", true);
        // 复制文件夹
        qDebug() << FileMgr::GetInstance().copyDir("./oldDir", "./newDir", true);
        // 删除文件
        qDebug() << FileMgr::GetInstance().delFileOrDir("./test2.json");
        // 删除文件夹
        qDebug() << FileMgr::GetInstance().delFileOrDir("./newDir");
        // 获取文件的MD5值
        qDebug() << FileMgr::GetInstance().getFileMd5("./test.json");
    
        return a.exec();
    }
    

    参考:

    Qt拷贝文件、文件夹、创建文件夹、删除文件夹操作

    Qt拷贝文件、文件夹(QFile::copy)

    QT删除文件夹或者文件

    QT 对文件的操作(创建、拷贝、写入、删除)


  • 相关阅读:
    python scrapter
    java Clone
    Burp Suite使用
    Drools 简单应用实例1
    Metasploitable 2 备译
    java drools material
    设计模式之Facade/Adaptor/Proxy示例
    sqlmap example
    Mutillidae setup
    groovy template应用
  • 原文地址:https://www.cnblogs.com/linuxAndMcu/p/14551139.html
Copyright © 2011-2022 走看看