如何解决文件的中文乱码问题

如何解决文件的中文乱码问题

HarmonyOS
2024-01-21 14:15:46
浏览
收藏 0
回答 3
回答 3
按赞同
/
按时间
鱼弦CTO
1
分享
微博
QQ
微信
回复
2024-07-10 11:14:40
lhlrj

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

import { util } from "@kit.ArkTS" 
import { fileIo } from '@kit.CoreFileKit'; 
 
let filePath = getContext(this).filesDir + "/test0.txt"; 
let stream = fileIo.createStreamSync(filePath, "r+"); 
let buffer = new ArrayBuffer(4096); 
let readOut = stream.readSync(buffer); 
let textDecoder = util.TextDecoder.create('utf-8', { ignoreBOM: true }); 
let readString = textDecoder.decodeWithStream(new Uint8Array(buffer), { stream: false }); 
console.log("读取的文件内容:" + readString);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

已于2024-1-31 14:02:04修改
分享
微博
QQ
微信
回复
2024-01-22 16:59:35
热辣牛奶

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

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

// 创建一个文件写入中文字符

let filePath = getContext(this).filesDir + "/test0.txt";
let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
  • 1.
  • 2.

// 写入一段内容至文件

let writeLen = fileIo.writeSync(file.fd, "你好,世界");
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);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

// 设置编码格式为“utf-8”

let textDecoder = util.TextDecoder.create('utf-8', { ignoreBOM: true });
  • 1.

// 解码输后获取对应文本

let readString = textDecoder.decodeWithStream(new Uint8Array(buffer), { stream: false });
console.info(`GarbledCnCharacters read content is:${readString}`);
  • 1.
  • 2.
分享
微博
QQ
微信
回复
2024-07-08 15:05:00
相关问题
HarmonyOS toast问题如何解决
1794浏览 • 1回复 待解决
this传递问题,该如何解决
2892浏览 • 1回复 待解决
如何解决预览流黑屏问题
2020浏览 • 1回复 待解决
Gauge组件问题,该如何解决
1118浏览 • 1回复 待解决
如何解决底层库无法调试问题
1684浏览 • 1回复 待解决
HarmonyOS如何解决数据存储问题
9911浏览 • 3回复 已解决
事件分发冲突问题如何解决
1158浏览 • 1回复 待解决
HarmonyOS路由问题如何解决
1067浏览 • 1回复 待解决
如何解决webview loaddata白屏问题
1935浏览 • 1回复 待解决
DevEco Studio IDE 代码 中文汉字乱码
13722浏览 • 2回复 待解决
HarmonyOS 字节数组转中文出现乱码
800浏览 • 1回复 待解决
har多目标,多值问题如何解决
1083浏览 • 1回复 待解决
如何解决webview离线加载白屏问题
2122浏览 • 1回复 待解决