Qfile与QTextStream读写文本文件

Qfile读取文本文件:

void readwrite::readfile()
{
	QString path = QFileDialog::getOpenFileName(this, "open", "../", "txt(*.txt)");//读取文件路径
	if (!path.isEmpty())
	{
		QFile file(path);
		bool isok = file.open(QIODevice::ReadOnly);//打开方式为只读
		if (isok)
		{
			QByteArray array = file.readAll();//读取文本中全部文件
			ui.textBrowser->setText(QString(array));
		}
		file.close();//关闭文件
	}
}

Qfile写出文本文件:

void readwrite::writefile()
{
	QString path = QFileDialog::getSaveFileName(this, "save", "../", "txt(*.txt)");//写出文件的路径
	if (!path.isEmpty())
	{
		QFile file(path);
		bool isok = file.open(QIODevice::WriteOnly);//打开方式为只写
		if (isok)
		{
			QString str = ui.textBrowser->toPlainText();//获取文本框中的内容
			file.write(str.toUtf8());
		}
		file.close();
	}
}

QTextStream读取文本文件:

void readwrite::readfile()
{
	QString path = QFileDialog::getOpenFileName(this, "open", "../", "txt(*.txt)");
	if (!path.isEmpty())
	{
		QFile file(path);
		bool isok = file.open(QIODevice::ReadOnly);
		if (isok)
		{
			QTextStream filestream(&file);//QTextStream 与file关联
			QString str;
			filestream.setCodec("UTF-8");
			while (filestream.atEnd()==false)
			{
				str.append(filestream.readLine());//逐行读取
				str.append("\n");
				//str = filestream.readAll();//一次性读取全部文件
			}
			ui.textBrowser->setText(str);
		}
		file.close();
	}
}

QTextStream写出文本文件:

void readwrite::writefile()
{
	QString path = QFileDialog::getSaveFileName(this, "save", "../", "txt(*.txt)");
	if (!path.isEmpty())
	{
		QFile file(path);
		bool isok = file.open(QIODevice::WriteOnly);
		if (isok)
		{
			QTextStream filestream(&file);//QTextStream 与file关联
			QString str = ui.textBrowser->toPlainText();
			filestream << str;//写出文件
			qDebug() << str;
		}
		file.close();
	}	
}

使用Qt读写文本文件通常使用Qfile与QTextStream 结合,因为QTextStream 可以逐行读取,对于处理数据要相对方便一些,而且Qt提供了较多的函数接口,较C++要更快速便捷。

你可能感兴趣的:(Qt)