QIODevice :: read:设备未打开

时间:2017-01-10 00:42:00

标签: json qt qfile

我终于找到了一个路径文件QFile会接受使用QFile.exist()和健康剂量的反复试验。

我想知道为什么以下有效:

#include <QFile>
#include <QByteArray>
#include <QJsonObject>
#include <QJsonDocument>

QString path = QDir::currentPath();     // Get current dir
path.append("/noteLibrary.json");

QFile file(path);           // Give QFile current dir + path to file
if (!file.exists()) {       // Check to see if QFile found the file at given file_path
    qDebug() << "NO FILE HERE";
}
qDebug() << path;           // See what path was finally successful
file.open(QIODevice::ReadOnly);      // Continue parsing document to confirm everything else is functioning normally.
QByteArray rawData = file.readAll();

// Parse document
QJsonDocument doc(QJsonDocument::fromJson(rawData));

// Get JSON object
QJsonObject json = doc.object();

// Access properties
qDebug() << json["die"].toString();     // Should output "280C4"

成功输出:

"/home/pi/noteLibrary.json"
"280C4"

但以下不起作用:

#include <QFile>
#include <QByteArray>
#include <QJsonObject>
#include <QJsonDocument>

QFile file("/home/pi/noteLibrary.json");           // Give QFile current dir + path to file
if (!file.exists()) {       // Check to see if QFile found the file at given file_path
    qDebug() << "NO FILE HERE";
}

//qDebug() << path;           // See what path was finally successful
file.open(QIODevice::ReadOnly);      // Continue parsing document to confirm everything else is functioning normally.
QByteArray rawData = file.readAll();

// Parse document
QJsonDocument doc(QJsonDocument::fromJson(rawData));

// Get JSON object
QJsonObject json = doc.object();

// Access properties
qDebug() << json["die"].toString();     // Should output "280C4"

错误输出:

NO FILE HERE
QIODevice::read (QFile, "/home/pi/Desktop/noteLibrary.json"): device not open
""

为什么QFile会以不同方式对待这些?这是QString格式问题吗?或者我将这个远程部署到Raspberry Pi 3的事实可能是罪魁祸首?

1 个答案:

答案 0 :(得分:0)

无论上面的代码出了什么问题,使用下面给出QFile的代码,绝对路径对使用currentPath()创建QString同样有效。我一定有别的错,我的错误!

noteLibrary.json

{"note": [{
             "profile": "C4",
             "die": "280C4",
             "pressure": 800,
             "position": 10000
         },
         {
             "profile": "CC4",
             "die": "2280C4",
             "pressure": 8800,
             "position": 110000
         }

    ],
    "test": {
        "profile": "CCC4",
        "die": "22280C4",
        "pressure": 88800,
        "position": 1110000
    }
}

main.cpp 摘录

    QFile file("/home/pi/noteLibrary.json");
    if (!file.exists()) qDebug() << "NO FILE FOUND";
    file.open(QIODevice::ReadOnly);
    QByteArray rawData = file.readAll();
    QJsonDocument doc(QJsonDocument::fromJson(rawData));    // Parse document
    QJsonObject jObj = doc.object();    // Get JSON object
    qDebug() << jObj["test"];

应用程序输出

QJsonValue(object,QJsonObject({"die":"22280C4","position":1110000,"pressure":88800,"profile":"CCC4"}))

奇怪的是,它按字母顺序显示属性值,而不是文档中列出的顺序。