首先各种方法输出结果,判断文件或者文件夹是否存在测试代码。
QFile还可以判断是相对路径、快捷方式、拷贝、重命名、移除、移动到回收站、创建快捷方式、设置文件权限、解析快捷方式目标文件等。
QFileInfo可以获取文件名(含后缀)、文件路径、文件绝对路径、文件当前系统下的规范路径、文件路径(不包括文件名)、后缀、文件名(不包含文件后缀),以及文件属性,可读、可写、隐藏等。
QFileInfo fi("D:/zp"); // 目录存在或者D:/zp/,如果目录不存在都是false
qDebug() << fi.isFile(); // false
qDebug() << fi.isDir(); // true
qDebug() << fi.exists(); // true
qDebug() << fi.isRoot(); // false
qDebug() << QFile::exists("D:/zp"); // true
qDebug() << QDir("D:/zp").exists(); // true
fi.setFile("D:/"); // 存在的驱动器,不存在的驱动器都是false
qDebug() << fi.isFile(); // false
qDebug() << fi.isDir(); // true
qDebug() << fi.exists(); // true
qDebug() << fi.isRoot(); // true
qDebug() << QFile::exists("D:/"); // true
qDebug() << QDir("D:/").exists(); // true
fi.setFile("D:/zp.lnk"); // 快捷方式存在且指向的文件也存在,快捷方式存在但指向的文件不存在都是false
qDebug() << fi.isFile(); // true
qDebug() << fi.isDir(); // false
qDebug() << fi.exists(); // true
qDebug() << QFile::exists("D:/zp.lnk"); // true
qDebug() << QDir("D:/zp.lnk").exists(); // false
可以看到,容易让人感到混乱的是exists方法,这个方法是通用的判断方法,可以看成是这样的表达式 exists() == (isFile() || isDir()) 。判断文件或文件夹是否存在单纯用exists方法是不严谨的,比如你的本意是判断文件是否存在,但文件不存在,而恰巧有个同名的文件夹,那么exists也会返回true。文件夹也是同理。根据上面的代码作出的一点总结:
- 准确判断文件是否存在,用QFileInfo::isFile() 。
- 准确判断文件夹是否存在,用QFileInfo::isDir()或者QDir::exists() 。
- 只需要确定字符串是文件/文件夹,用QFileInfo::exists()或者QFile::exists()。
封装方法:
- 判断文件夹是否是存在
//QString Path;//文件夹全路径
//方法1
static bool IsDirExist(QString path)
{
QDir dir(path);
return dir.exists();
}
//方法2
static bool IsDirExist(QString path)
{
QFileInfo fileInfo(path);
return fileInfo.isDir();
}
- 判断文件是否是存在
//QString filePath;//文件全路径
//方法1
static bool IsFileExist(QString filePath)
{
QFileInfo fileInfo(filePath);
if(fileInfo.isFile())
{
return true;
}
return false;
}
3、判断文件或文件夹是否是存在(即不确定字符串是文件还是文件夹路径)
//QString filePath;//路径名
//方法1
static bool IsFileExist(QString filePath)
{
QFileInfo fileInfo(filePath);
return fileInfo.exists();
}
//方法2
static bool IsFileExist(QString filePath)
{
QFile file(filePath);
return file.exists();
}
4、判断文件夹是否存在,不存在则创建
//方法1
static bool IsDirExist(QString fullPath)
{
QDir dir(fullPath);
if(dir.exists())
{
return true;
}
else
{
bool ok = dir.mkdir(fullPath);//只创建一级子目录,即必须保证上级目录存在
return ok;
}
}
//方法2
static bool IsDirExist(QString fullPath)
{
QDir dir(fullPath);
if(dir.exists())
{
return true;
}
else
{
bool ok = dir.mkpath(fullPath);//创建多级目录
return ok;
}
}