Files
GenericQtClientCore/data/filehandler.cpp

54 lines
1.5 KiB
C++

#include "filehandler.h"
#include <QDebug>
#include <QDir>
#include <QJsonDocument>
#include <QStandardPaths>
bool FileHandler::saveToFile(const QJsonDocument& doc, const QString& fileName) {
qDebug() << "saving file...";
QString path = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation).at(0);
qDebug() << path;
QDir dir;
if (!dir.exists(path)) {
dir.mkpath(path);
}
// qDebug() << path + fileName;
const QString filePath = path + '/' + fileName;
QFile file(filePath);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
qWarning() << "can't open file";
return false;
}
QTextStream out(&file);
out.setEncoding(QStringConverter::Utf8);
out << doc.toJson(QJsonDocument::Indented);
return true;
}
QByteArray FileHandler::loadJSONDataFromFile(const QString fileName) {
QByteArray jsonData;
QFile file;
QString path = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation).at(0);
file.setFileName(path + "/" + fileName);
if (file.exists()) {
qDebug() << "File found, reading content...";
const bool successfulOpened = file.open(QIODevice::ReadOnly | QIODevice::Text);
if (successfulOpened) {
// TODO learn and decide on the differences between "readAll" and using
// streams
jsonData = file.readAll();
file.close();
} else {
qWarning() << "File could not be opened!";
}
} else {
qInfo() << "File not found. Returning empty result...";
}
return jsonData;
}
FileHandler::FileHandler() {}