INI文件处理
首先得引入QSettings
QSettings 是用来存储和读取应用程序设置的一个类
#include "wrinifile.h"
#include <QSettings>
#include <QtDebug>
写配置文件
void WriteIniFiles()
{
//QSettings用来存储和读取应用程序设置的一个类
// 直接使用QSettings类读写INI文件
//只给出了文件名,像 "MySQLFiles.ini",那么配置文件会被存放在应用程序的工作目录下
//从 Qt 5.15 版本开始,QSettings 默认采用 UTF-8 编码
QSettings *ConfigWriteIniFiles=new QSettings("MySQLFiles.ini",QSettings::IniFormat);
/*
QSettings::IniFormat 指定配置文件使用 INI 格式存储。
INI 格式是一种文本格式,由节 (sections) 和键值对 (key-value pairs) 组成,
便于人类阅读和编辑。这种格式在 Windows 系统中传统上用于存储应用程序设置,现在也被广泛用于跨平台应用。
*/
// 向INI文件当中写入数据信息
// 第一节的第一参数,后面就依次类推
ConfigWriteIniFiles->setValue("/database/ip","192.168.12.189");
ConfigWriteIniFiles->setValue("/database/port","3308");
ConfigWriteIniFiles->setValue("/database/user","root");
ConfigWriteIniFiles->setValue("database/password","123456");
//写到文件中的格式
/*
[database]
ip=192.168.12.189
port=3308
user=root
password=123456
*/
ConfigWriteIniFiles->setValue("/notice/version","5.6");
ConfigWriteIniFiles->setValue("/notice/datetime","2022-10-25 16:27:23");
/*
[notice]
version=5.6
datetime=2022-10-25 16:27:23
*/
//获取MySQLFiles.ini文件路径
qDebug() << ConfigWriteIniFiles->fileName();
// 向IN文件写入完成之后,删除指针
delete ConfigWriteIniFiles;
}
读配置文件
void ReadIniFiles()
{
QSettings *ConfigReadIniFiles=new QSettings("MySQLFiles.ini",QSettings::IniFormat);
//QSettings->value("....") 返回的是一个 QVariant 对象,而不是直接的字符串
QString strip=ConfigReadIniFiles->value("/database/ip").toString();
QString strport=ConfigReadIniFiles->value("/database/port/").toString();
QString struser=ConfigReadIniFiles->value("/database/user").toString();
QString strpassword=ConfigReadIniFiles->value("/database/password").toString();
QString strversion=ConfigReadIniFiles->value("/notice/version").toString();
QString strdatetime=ConfigReadIniFiles->value("/notice/datetime").toString();
/*
QString::toUtf8()将字符串转换为UTF-8编码的QByteArray,
其.data()返回的char*是合法的UTF-8字节流,与终端编码匹配(假设终端支持UTF-8)。
*/
qDebug()<<"正确--------";
qDebug()<<"读取INI配置文件参数选项如下:";
qDebug()<<"MySQL数据库IP地址:"<<strip.toUtf8().data();
qDebug()<<"数据库端口:"<<strport.toUtf8().data();
qDebug()<<"数据库用户:"<<struser.toUtf8().data();
qDebug()<<"数据库密码:"<<strpassword.toUtf8().data();
qDebug()<<"数据库版本:"<<strversion.toUtf8().data();
qDebug()<<"数据库日期:"<<strdatetime.toUtf8().data();
/*
QString::data()返回的是QChar*(指向UTF-16数据的指针),直接转换为char*时,
每个QChar(16位)会被拆分为两个char(8位),导致字节顺序和编码混乱。
*/
qDebug()<<"错误--------";
qDebug()<<"读取INI配置文件参数选项如下:";
qDebug()<<"MySQL数据库IP地址:"<<strip.data();
qDebug()<<"数据库端口:"<<strport.data();
qDebug()<<"数据库用户:"<<struser.data();
qDebug()<<"数据库密码:"<<strpassword.data();
qDebug()<<"数据库版本:"<<strversion.data();
qDebug()<<"数据库日期:"<<strdatetime.data();
// 将读取配置文件完成之后,删除指针
delete ConfigReadIniFiles;
}
void ReadIniFilesIsKey()
{
QSettings setting("./MySQLFiles.ini",QSettings::IniFormat);
//返回所有已存储设置的完整键名列表,包括子组中的键
foreach(QString key,setting.allKeys())
{
qDebug()<<key.toUtf8().data()<<":"<<setting.value(key).toString().toUtf8().data();
}
}
JSON 文件处理
头文件引入
#include <QMessageBox>
#include <QDebug>
#include <QFile> // 文件读写
#include <QJsonDocument> // JSON文档
#include <QJsonObject> // JSON对象
#include <QJsonParseError> // JSON异常捕捉
写入JSON
// 将数据信息-->写入JSON文件
void QJsonOper::on_pushButtonWriteJson_clicked()
{
// 1:创建json对象
QJsonObject mysqinfo;
//插入键值对
mysqinfo.insert("ip","192.168.0.125");
mysqinfo.insert("port",3308);
mysqinfo.insert("user","root");
mysqinfo.insert("password","123456");
QJsonObject jsonifo;
jsonifo.insert("code",1);
jsonifo.insert("dbmsg","MySQL数据库配置参数");
// 将json对象作为Json对象插入的数据值
jsonifo.insert("data",mysqinfo);
// 2: 创建JSON文档
//QJsonDocument 用于将 Qt 的数据结构序列化为 JSON 文本 和 反序列化
QJsonDocument jsondoc;
jsondoc.setObject(jsonifo);
// 3: 创建文件
QFile qfiles("./databasejsonfiles.json");
if(qfiles.open(QIODevice::WriteOnly))
{
qfiles.write(jsondoc.toJson());
qfiles.close();
qDebug()<<"恭喜你,json数据文件写入成功!";
}
QMessageBox::information(this,"写入成功","恭喜你,json数据文件写入成功!");
}
读取JSON
void QJsonOper::on_pushButtonReadJson_clicked()
{
QString strjson;
QString strmsg;
QFile qfiles("./databasejsonfiles.json");
if(qfiles.open(QIODevice::ReadOnly))
{
strjson=qfiles.readAll();
qfiles.close();
}
QJsonParseError jsonerror; // 返回JSON解析错误的时候,报告错误信息
//把 JSON 格式的文本解析成 Qt 能够处理的数据结构
QJsonDocument jsondoc=QJsonDocument::fromJson(strjson.toUtf8(),&jsonerror);
if(!jsondoc.isEmpty() && (jsonerror.error==QJsonParseError::NoError))
{
// 只要jsondoc不为空,和jsonerror没有错误
// 将它转换为JSON对象
QJsonObject json=jsondoc.object();
QJsonValue code=json.value("code");
QJsonValue data=json.value("data");
// QJsonValue .isUndefined()
//用于检查 QJsonValue 对象是否为未定义状态的方法。在 JSON 处理中,未定义状态不同于空值(null),它表示该 JSON 值从未被显式设置过。
if(code.isUndefined() || code.toDouble()!=1 || data.isUndefined() || !data.isObject())
{
qDebug()<<"转换JSON数据错误,请重新检查?";
QMessageBox::critical(this,"错误","转换JSON数据错误,请重新检查?");
exit(100);
}
// 如果没有错误,读取data数据信息
QJsonObject databaseinfo=data.toObject();
QJsonValue dbip=databaseinfo.value("ip");
QJsonValue dbport=databaseinfo.value("port");
QJsonValue dbuser=databaseinfo.value("user");
QJsonValue dbpassword=databaseinfo.value("password");
//判断 data JSON 值是否未定义
if(dbip.isUndefined()||
dbport.isUndefined()||
dbuser.isUndefined()||
dbpassword.isUndefined())
{
qDebug()<<"接口错误,请重新检查?";
QMessageBox::critical(this,"错误","接口错误,请重新检查?");
exit(100);
}
QString strip=dbip.toString();
int iport=dbport.toInt();
QString struser=dbuser.toString();
QString strpassword=dbpassword.toString();
// 判断每一项配置是否为空
if(strip.isEmpty() || struser.isEmpty() || strpassword.isEmpty())
{
qDebug()<<"此数据项不能为空,请重新检查?";
QMessageBox::critical(this,"错误","此数据项不能为空,请重新检查?");
exit(100);
}
qDebug()<<"数据库IP地址:"<<strip;
qDebug()<<"数据库端口:"<<iport;
qDebug()<<"数据库用户:"<<struser;
qDebug()<<"数据库密码:"<<strpassword;
// 拼接字符串
strmsg+="【JSON配置参数】";
strmsg+="\n数据库IP地址:"+strip;
strmsg+="\n数据库端口:"+QString::number(iport,10);
strmsg+="\n数据库用户:"+struser;
strmsg+="\n数据库密码:"+strpassword;
}
QMessageBox::information(this,"成功",strmsg,QMessageBox::Yes);
}
XML文件处理
引入头文件
// QDomComment是专门用来操作XML文件(项目中用来存储一些配置数据信息)
#include <QDomComment>
写XML文件
ReadWriteXml::ReadWriteXml(QWidget *parent)
: QDialog(parent)
, ui(new Ui::ReadWriteXml)
{
ui->setupUi(this);
//QString
strcurrentfilepath="d:/xmlfiles"; // xml文件路径
strcurrentfilename="/factoryworkersxml.xml";
}
bool ReadWriteXml::openxmlfiles(QString filenamepath) // 打开指定文件
{
// 如果没有,则创建文件
m_qfiles.setFileName(strcurrentfilepath+filenamepath);
return m_qfiles.open(QIODevice::ReadWrite | QFile::Text);
}
void ReadWriteXml::writexmlfiles() // 写入xml文件
{
if(!openxmlfiles(strcurrentfilename))
{
qDebug()<<"写入:打开XML文件失败,请重新检查?";
return;
}
qDebug()<<"写入:打开XML文件成功,请认真操作xml!";
//Qt 框架里用于处理 XML 文档的类,它以 DOM(文档对象模型)方式呈现 XML 文档
QDomDocument domdoct; // 创建对象
//QDomProcessingInstruction 是 Qt 框架中用于处理 XML 处理指令
QDomProcessingInstruction version; // 写入xml头部(添加处理命令)
version=domdoct.createProcessingInstruction("xml","version = \"1.0\" encoding = \"GB2312\"");
domdoct.appendChild(version);
// 添加第1个子节点及相关子元素
QDomElement domrootelement=domdoct.createElement("factory"); // 创建顶层节点
domdoct.appendChild(domrootelement);
QDomElement itemrootelement=domdoct.createElement("worker"); // 创建父节点
{
// 创建子元素
QDomElement node1=domdoct.createElement("WNo"); // 创建子节点(创建元素节点)
QDomText domtext1=domdoct.createTextNode("WNo"); // 可创建文本节点
domtext1.setData(ui->lineEdit_No->text()); // 设置子节点数据
node1.appendChild(domtext1); // 将子节点数据进行绑定
itemrootelement.appendChild(node1); // 将子节点绑定到父亲节点
QDomElement node2=domdoct.createElement("WName"); // 创建子节点(创建元素节点)
QDomText domtext2=domdoct.createTextNode("WName"); // 可创建文本节点
domtext2.setData(ui->lineEdit_Name->text()); // 设置子节点数据
node2.appendChild(domtext2); // 将子节点数据进行绑定
itemrootelement.appendChild(node2); // 将子节点绑定到父亲节点
QDomElement node3=domdoct.createElement("WSex"); // 创建子节点(创建元素节点)
QDomText domtext3=domdoct.createTextNode("WSex"); // 可创建文本节点
domtext3.setData(ui->lineEdit_Sex->text()); // 设置子节点数据
node3.appendChild(domtext3); // 将子节点数据进行绑定
itemrootelement.appendChild(node3); // 将子节点绑定到父亲节点
QDomElement node4=domdoct.createElement("WEducation"); // 创建子节点(创建元素节点)
QDomText domtext4=domdoct.createTextNode("WEducation"); // 可创建文本节点
domtext4.setData(ui->lineEdit_Education->text()); // 设置子节点数据
node4.appendChild(domtext4); // 将子节点数据进行绑定
itemrootelement.appendChild(node4); // 将子节点绑定到父亲节点
QDomElement node5=domdoct.createElement("WDepartment"); // 创建子节点(创建元素节点)
QDomText domtext5=domdoct.createTextNode("WDepartment"); // 可创建文本节点
domtext5.setData(ui->lineEdit_Department->text()); // 设置子节点数据
node5.appendChild(domtext5); // 将子节点数据进行绑定
itemrootelement.appendChild(node5); // 将子节点绑定到父亲节点
QDomElement node6=domdoct.createElement("WSalary"); // 创建子节点(创建元素节点)
QDomText domtext6=domdoct.createTextNode("WSalary"); // 可创建文本节点
domtext6.setData(ui->lineEdit_Salary->text()); // 设置子节点数据
node6.appendChild(domtext6); // 将子节点数据进行绑定
itemrootelement.appendChild(node6); // 将子节点绑定到父亲节点
}
domrootelement.appendChild(itemrootelement); // 绑定到顶层节点
m_qfiles.write(domdoct.toString().toLocal8Bit().data());
m_qfiles.close();
QMessageBox::information(this,"提示","恭喜你,写入XML文件数据成功,请查看目录文件?",QMessageBox::Yes);
}
读XML文件
void ReadWriteXml::readxmlfiles() // 读取xml文件
{
if(!openxmlfiles(strcurrentfilename))
{
qDebug()<<"读取:打开XML文件失败,请重新检查?";
return;
}
qDebug()<<"读取:打开XML文件成功,请认真操作xml!";
QDomDocument docs;
//于解析 XML 数据并将其设置为 DOM(文档对象模型)树的方法
//QDomDocument::setContent() 函数在解析 XML 时会自动跳过 XML 处理指令 ( 以 <? 开头、?> )
//<?xml version = "1.0" encoding = "GB2312"?>
if(!docs.setContent(&m_qfiles))
{
m_qfiles.close();
qDebug()<<"读取:操作setContent失败,请重新检查?";
return;
}
qDebug()<<"读取:操作setContent成功,请认真操作!";
// 读取根节点
QDomElement root=docs.documentElement();
// 读取第1个父亲节点
QDomNode node=root.firstChild();
while(!node.isNull())
{
QDomNodeList sonlist=node.childNodes(); // 读取子结点集合信息
QString rootname=node.toElement().tagName(); // 读取父亲节点名称
if(rootname.compare("worker")==0)
{
// 将子节点集合信息传递到读取子节点数据
readrootxml(sonlist);
}
node=node.nextSibling(); // 读取下一个父节点
}
}
void ReadWriteXml::readrootxml(QDomNodeList sonnodelist) // 读取子节点数据
{
for(int sonnode=0;sonnode<sonnodelist.size();sonnode++)
{
// 获取子节点
QDomElement sonelement=sonnodelist.at(sonnode).toElement();
if(sonelement.toElement().tagName().compare("WNo")==0) // 取出子节点进行比较
{
ui->lineEdit_No_R->setText(sonelement.text());
}
else if(sonelement.toElement().tagName().compare("WName")==0)
{
ui->lineEdit_Name_R->setText(sonelement.text());
}
else if(sonelement.toElement().tagName().compare("WSex")==0)
{
ui->lineEdit_Sex_R->setText(sonelement.text());
}
else if(sonelement.toElement().tagName().compare("WEducation")==0)
{
ui->lineEdit_Education_R->setText(sonelement.text());
}
else if(sonelement.toElement().tagName().compare("WDepartment")==0)
{
ui->lineEdit_Department_R->setText(sonelement.text());
}
else if(sonelement.toElement().tagName().compare("WSalary")==0)
{
ui->lineEdit_Salary_R->setText(sonelement.text());
}
}
}