QIODevice::read : 设备未打开

QIODevice::read : device not open

我终于找到了一个 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 可能是罪魁祸首?

不管我上面的代码有什么问题,下面的代码为 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"}))

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