1.代碼文件本身編碼;
2.Qt中用於控制讀入和寫出文件系統時的字符編碼由QTextCodec::setCodecForLocale()所決定。一般不用設置,Qt跟系統交互時會根據系統的Locale來更改傳給系統的參數的編碼;
//utf8格式
QString str1("你好Hello\r\n");
QByteArray bLocal = str1.toLocal8Bit(); // 受setCodecForLocale影響,會轉換為設定的編碼。如果本機不支持指定編碼,則會按toLatin1處理
QByteArray bUtf8 = str1.toUtf8(); // 不受setCodecForLocale影響,強制轉換為UTF-8編碼
qDebug() << str1; // 正常,Qt會將UTF-16轉換為UTF-8輸出
qDebug() << bLocal; // 亂碼,用UTF-8編碼輸出GBK字節流
qDebug() << bUtf8; // 正常,用UTF-8編碼輸出UTF-8字節流
QString str2 = QString::fromLocal8Bit(bLocal);
qDebug() << str2; // 正常,因為上面顯式指定字節流來自本機編碼,而bLocal正是本機編碼GBK
QString strTitle("你好Hello");
QFile file(strTitle);
if(!file.open(QIODevice::WriteOnly|QIODevice::Append))
return false;
file.write(QString::fromUtf8("你好啊Hello測試中\r\n").toLocal8Bit());
file.write(bUtf8);
file.write(bLocal);
file.write("1122測試中\r\n");
file.write(QString::fromUtf8("你好啊Hello\r\n").toLocal8Bit());
file.close();
//gbk格式
QString str1=QString::fromLocal8Bit("你好Hello\r\n");
QByteArray bLocal = str1.toLocal8Bit(); // 受setCodecForLocale影響,會轉換為設定的編碼。如果本機不支持指定編碼,則會按toLatin1處理
QByteArray bUtf8 = str1.toUtf8(); // 不受setCodecForLocale影響,強制轉換為UTF-8編碼
qDebug() << str1; // 正常,Qt會將UTF-16轉換為UTF-8輸出
qDebug() << bLocal; // 亂碼,用UTF-8編碼輸出GBK字節流
qDebug() << bUtf8; // 正常,用UTF-8編碼輸出UTF-8字節流
QString str2 = QString::fromLocal8Bit(bLocal);
qDebug() << str2; // 正常,因為上面顯式指定字節流來自本機編碼,而bLocal正是本機編碼GBK
QString strTitle=QString::fromLocal8Bit("你好Hello");
QFile file(strTitle);
if(!file.open(QIODevice::WriteOnly|QIODevice::Append))
return false;
file.write(QString::fromLocal8Bit("你好啊Hello測試中\r\n").toLocal8Bit());
file.write(bUtf8);
file.write(bLocal);
file.write("1122測試中\r\n");
file.write(QString::fromLocal8Bit("你好啊Hello\r\n").toLocal8Bit());
file.close();