86 lines
2.4 KiB
C++
86 lines
2.4 KiB
C++
#include "filehandler.h"
|
|
|
|
#include <QDebug>
|
|
#include <QDir>
|
|
#include <QJsonDocument>
|
|
#include <QStandardPaths>
|
|
|
|
#include "../formats/csvparser.h"
|
|
|
|
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) {
|
|
QFile file;
|
|
QString path = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation).at(0);
|
|
file.setFileName(path + "/" + fileName);
|
|
|
|
QPair<QString, QByteArray> fileContent = getFileContent(path + "/" + fileName);
|
|
|
|
return fileContent.second;
|
|
}
|
|
|
|
QList<ModelItemValues> FileHandler::getItemValuesFromCSVFile(const QString& filePath) {
|
|
QList<ModelItemValues> result;
|
|
QFile file;
|
|
file.setFileName(filePath);
|
|
if (file.exists()) {
|
|
result = CsvParser::getItemsFromCSVFile(filePath);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
FileHandler::FileHandler() {}
|
|
|
|
/** Tries to open the file specified by the file path & returns the content
|
|
* @brief FileHandler::getFileContent
|
|
* @param filePath
|
|
* @return Returns an error string (empty if successful) and the file content
|
|
*/
|
|
QPair<QString, QByteArray> FileHandler::getFileContent(const QString& filePath) {
|
|
QString errorString = "";
|
|
|
|
QByteArray fileContent;
|
|
QFile file;
|
|
file.setFileName(filePath);
|
|
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
|
|
fileContent = file.readAll();
|
|
file.close();
|
|
} else {
|
|
errorString = "File could not be opened!";
|
|
qWarning() << errorString;
|
|
}
|
|
} else {
|
|
errorString = "File not found. Returning empty result...";
|
|
qInfo() << errorString;
|
|
}
|
|
|
|
const QPair<QString, QByteArray> result(errorString, fileContent);
|
|
return result;
|
|
}
|