一、读文件
#include "widget.h"
#include "ui_widget.h"
#include <QFileDialog>
#include <QDebug>
#include <QMessageBox>
#include <QFile>
#include <QTextCodec>
Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{
ui->setupUi(this);
connect(ui->pushButton,&QPushButton::clicked,this,[=](){
QString filePath = QFileDialog::getOpenFileName(this,"打开文件","C:\\Users\\Admin\\Desktop","(*.txt)"); //后两个参数为:默认打开的路径、筛选的文件格式
if (filePath.isEmpty())
{
QMessageBox::warning(this,"警告","路径不能为空!");
}
else
{
ui->lineEdit->setText(filePath);
QFile file(filePath);
file.open(QIODevice::ReadOnly);
QByteArray messageFile1 = file.readAll();
// QByteArray messageFile2 = file.readLine();
// if (!file.atEnd())
// {
// messageFile2 += file.readLine();
// }
QTextCodec* codec = QTextCodec::codecForName("UTF-8");
ui->textEdit->setText(codec->toUnicode(messageFile1)); //默认支持UTF-8格式
file.close();
}
});
}
二、写文件
#include "widget.h"
#include "ui_widget.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QFile>
Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{
ui->setupUi(this);
connect(ui->pushButton,&QPushButton::clicked,this,[=](){
QString filePath = QFileDialog::getOpenFileName(this,"打开文件","C:\\Users\\Admin\\Desktop","(*.txt)"); //后两个参数为:默认打开的路径、筛选的文件格式
if (filePath.isEmpty())
{
QMessageBox::warning(this,"警告","路径不能为空!");
}
else
{
ui->lineEdit->setText(filePath);
QFile file(filePath);
// file.open(QIODevice::WriteOnly); //会将原本的文本覆盖
// file.write("路明非");
file.open(QIODevice::Append);
file.write("路明非!!!!!!!!!!");
file.close();
}
});
}
三、QFileInfo——文件信息
#include "widget.h"
#include "ui_widget.h"
#include <QFileDialog>
#include <QDebug>
#include <QMessageBox>
#include <QFile>
#include <QFileInfo>
#include <QDateTime>
Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{
ui->setupUi(this);
connect(ui->pushButton,&QPushButton::clicked,this,[=](){
QString filePath = QFileDialog::getOpenFileName(this,"打开文件","C:\\Users\\Admin\\Desktop","(*.txt)"); //后两个参数为:默认打开的路径、筛选的文件格式
if (filePath.isEmpty())
{
QMessageBox::warning(this,"警告","路径不能为空!");
}
else
{
ui->lineEdit->setText(filePath);
QFile file(filePath);
QFileInfo fileInfo(filePath);
qDebug() << "文件后缀名:" << fileInfo.suffix().toUtf8().data() << endl
<< "文件大小:" << fileInfo.size() << endl
<< "文件名:" << fileInfo.fileName() << endl
<< "文件路径:" << fileInfo.filePath();
qDebug() << "创建日期:" << fileInfo.birthTime().toString("yyyy-MM-dd hh:mm:ss") << endl //#include <QDateTime>
<< "最后一次修改日期:" << fileInfo.lastModified().toString("yyyy-MM-dd hh:mm:ss");
}
});
}