鸿蒙6.0开发常见问题【如何解决文件的中文乱码问题?】

读取文件内容的buffer数据后,通过TextDecoder对文件内容进行解码。

import { util } from '@kit.ArkTS';
import { fileIo } from '@kit.CoreFileKit';


// In the utility class, retrieve the Context from the Entry Ability and save it to AppStore, then use AppStore to retrieve it in the utility class
let context = AppStorage.get("context") as UIContext;
// Create a file to write Chinese characters
let filePath = context.getHostContext()!.filesDir + "/test0.txt";
let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
// Write a paragraph of content to a file
let writeLen = fileIo.writeSync(file.fd, "Hello, world");
fileIo.closeSync(file);
console.info(`GarbledCnCharacters The length of str is: ${writeLen}`);
let stream = fileIo.createStreamSync(filePath, "r+");
let buffer = new ArrayBuffer(4096);
stream.readSync(buffer);
// Set the encoding format to "utf-8"
let textDecoder = util.TextDecoder.create('utf-8', { ignoreBOM: true });
// Retrieve the corresponding text after decoding the input
let readString = textDecoder.decodeToString(new Uint8Array(buffer), { stream: false });
console.info(`GarbledCnCharacters read content is:${readString}`);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值