1、用到了QDir QDirIterator递归文件目录
2、QTextStream以某种编码格式读取文本保存到QString,然后以另一种编码格式保存文本
3、界面很简单,如下:
#include "widget.h"#include "ui_widget.h"#include <QFile>#include <QFileInfo>#include <QTextCodec>#include <QTextStream>#include <QDir>#include <QDirIterator>#include <QFileDialog>Widget::Widget(QWidget *parent) :QWidget(parent), ui(new Ui::Widget){ ui->setupUi(this); // 添加编码 QStringList items; items << "UTF-8"<<"GBK"; ui->comboBoxCodecSource->clear(); ui->comboBoxCodecDest->clear(); ui->comboBoxCodecSource->addItems(items); ui->comboBoxCodecSource->setCurrentText("GBK"); ui->comboBoxCodecDest->addItems(items); ui->comboBoxCodecDest->setCurrentText("UTF-8"); m_strTrPath = "";//目录路径}Widget::~Widget(){ delete ui;}void Widget::on_btnPRoject_clicked(){ static QString strDir = "d:/";//初始目录 strDir = QFileDialog::getExistingDirectory(this, tr("选择目录"), strDir, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); // 选择工程目录 if (!strDir.isEmpty()) { m_strTrPath = strDir; ui->labelStatus->setText(QString("选择目录[%1]").arg(strDir)); } else strDir = "d:/";}void Widget::on_btnChange_clicked()//点击开始转换按钮{ QDir dir (m_strTrPath); QDirIterator dirIterator(m_strTrPath, QDir::AllDirs | QDir::NoSymLinks | QDir::NoDotAndDotDot, QDirIterator::Subdirectories); ui->textBrowser->clear(); do { QStringList filters; filters << "*.pro" << "*.cpp" << "*.h"; dir.setPath(m_strTrPath); ui->textBrowser->append(QString("<span style=/" color:#FF0000;/">进入目录:</span> [ %1 ] <br>").arg(m_strTrPath)); // 转换文件 foreach (QFileInfo fileInfo, dir.entryInfoList(filters)) changeTextcodec(fileInfo.absoluteFilePath()); // 转换编码 } while (dirIterator.hasNext()&&(m_strTrPath = dirIterator.next())!="");}void Widget::changeTextcodec(QString fileName)//改变文本编码的关键代码,fileName是带路径的文件名{ QFile fileRead(fileName); fileRead.open(QIODevice::ReadOnly); QTextStream out(&fileRead); //这一句需要知道文本当前的编码格式 out.setCodec(QTextCodec::codecForName(ui->comboBoxCodecSource->currentText().toLatin1())); out.setAutoDetectUnicode(true); QString strTemp; QStringList strContents; while (!out.atEnd()) { strTemp = out.readLine(); strContents << strTemp; } fileRead.close(); QFile fielWrite(fileName); if (!fielWrite.open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Truncate)) { ui->labelStatus->setText("文件打开失败!"); return; } QTextStream in(&fielWrite); in.setCodec(QTextCodec::codecForName(ui->comboBoxCodecDest->currentText().toLatin1())); in.setAutoDetectUnicode(true); for (int i = 0; i < strContents.size(); i++) in << strContents.at(i) << endl; fielWrite.close(); ui->textBrowser->append(QString("<span style=/" color:#0000FF;/">转换完成:</span> [ %1 ] <br>").arg(fileName));}代码下载地址:http://download.csdn.net/detail/bladeandmaster88/9747442
新闻热点
疑难解答