qt 读写文本、xml文件
写txt文件
QString fileName = ui->lineEdit->text();
QString fileContent = ui->textEdit->toPlainText();
qDebug()<<"test:"<<fileContent;
QFile file(fileName);
if(!file.open(QFile::WriteOnly|QFile::Text))
{
qDebug()<<fileName<<"打开失败!"<<endl;
return;
}
QTextStream stream(&file);
stream<<fileContent;
file.close();
读txt 文件
QString fileName = ui->lineEdit->text();
QFile file(fileName);
if(!file.open(QFile::ReadOnly))
{
qDebug()<<fileName<<"打开失败!"<<endl;
return;
}
QTextStream stream(&file);
QString str = stream.readAll();
file.close();
ui->textEdit->setText(str);
写xml文件
QString fileName = ui->lineEdit->text();
if(fileName.isNull()||fileName.isEmpty())
{
QMessageBox::information(this,"提示","没有文件名");
return;
}
QFile file(fileName);
if(!file.open(QFile::Text|QFile::WriteOnly|QFile::Truncate))
{
qDebug()<<"文件打开失败!"<<endl;
return;
}
//写XML文件
QXmlStreamWriter writer(&file);
writer.setCodec("utf-8");
writer.setAutoFormatting(true);
writer.writeStartDocument();
writer.writeStartElement("person");
writer.writeStartElement("student");
QXmlStreamAttributes attribute;
attribute.append("class","class_one");
writer.writeAttributes(attribute);
writer.writeTextElement("name","xiaoli");
writer.writeTextElement("age","10");
writer.writeEndElement();
writer.writeEndElement();
file.close();
读xml 文件
QFile file1(fileName);
if(!file1.open(QFile::ReadOnly))
{
qDebug()<<"打开文件失败:"<<fileName<<endl;
}
//解析xml文件并写到label控件中
ui->label_3->setText("");//读文件前先清空显示控件
QXmlStreamReader reader(&file1);
while(!reader.atEnd())
{
if(reader.isStartElement())
{
if(reader.isComment())
qDebug() << "comment";
else if(reader.name()=="name")
{
QString str = ui->label_3->text();
str = str+" "+reader.readElementText();
ui->label_3->setText(str);
}
else if(reader.name()=="age")
{
QString str = ui->label_3->text();
str = str+" "+reader.readElementText();
ui->label_3->setText(str);
}
}
reader.readNext();
}
file1.close();