HarmonyOS 鸿蒙Next 下载bin文件保存为txt出现乱码
HarmonyOS 鸿蒙Next 下载bin文件保存为txt出现乱码
在使用 request.downloadFile 方法时,下载云端bin文件并保存到沙盒。结果会出现乱码。 正确输出结果16进制: 62696E494F5403023D6EE5F64088030004000000010000002304FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF(后面省略…)
示例代码:
export function downloadFiles(url: string, name: string): Promise<string> {
let filePath = filesDir + `/${name}.txt`
return new Promise((resolve, reject) => {
try {
request.downloadFile(context, {
url: url,
filePath: filePath
}).then((downloadTask: request.DownloadTask) => {
downloadTask.on('complete', () => {
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE);
fs.readText(filePath).then((str) => {
console.info(`The content of [file]: ${ 'binIOT\u0003\u0002=n嶀䀀\u0001#\u0004\uffff\uffff\uffff\uffff\uffff\uffff\n' }`); // 正确的结果 ‘binIOT\u0003\u0002=n嶀䀀\u0001#\u0004\uffff\uffff\uffff\uffff\uffff\uffff\n’
console.info(`The content of [file]: ${ str.slice(0,30) }`); // 错误的结果 ‘binIOT\u0003\u0002=n嶀ȃ\u0004\u0001#\u0004���’
resolve(str)
console.info("get file info succeed, the size of file is = " + str.length);
}).catch((err: BusinessError) => {
console.error("get file info failed with error message: " + err.message + ", error code: " + err.code);
});
fs.closeSync(file);
})
}).catch((err: BusinessError) => {
console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
});
} catch (error) {
let err: BusinessError = error as BusinessError;
console.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`);
}
})
}
let url: string = 'https://yadea-tsp.oss-cn-shanghai.aliyuncs.com/app/model3/393f5bb3584d413bb35d8259c7a0df69.bin'
downloadFile(this.otaUrl, 'test')
更多关于HarmonyOS 鸿蒙Next 下载bin文件保存为txt出现乱码的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
2 回复
使用记事本打开bin文件时,会出现乱码的情况。这是因为bin文件是一种二进制文件,而记事本是一种文本编辑器,无法正确解析二进制数据。直接下载链接中的文件使用记事本打开也是乱码的。
更多关于HarmonyOS 鸿蒙Next 下载bin文件保存为txt出现乱码的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
针对HarmonyOS 鸿蒙Next下载bin文件保存为txt出现乱码的问题,这通常是由于文件编码不一致导致的。bin文件是二进制文件,而txt文件是纯文本文件,两者在编码和存储方式上存在差异。
要解决此问题,请尝试以下步骤:
- 确认原始bin文件的编码:尽管bin文件本身不特定于某种文本编码,但了解其内容是否以特定方式编码(如ASCII、UTF-16等)有助于后续处理。
- 使用合适的工具转换编码:在HarmonyOS中,可以使用文件I/O API读取bin文件内容,并使用TextEncoder/TextDecoder或类似的库(如@ohos/juniversalchardet用于检测编码)将内容转换为合适的文本编码(如UTF-8),然后保存为txt文件。
- 检查并指定正确的保存编码:在保存txt文件时,确保指定了正确的编码格式(如UTF-8),以避免乱码问题。
如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html。