HarmonyOS 鸿蒙Next TXT文件读写 中文乱码
HarmonyOS 鸿蒙Next TXT文件读写 中文乱码
额外配置
C:\Users\XXX\AppData\Roaming\Huawei\DevEcoStudio3.1\devecostudio64.exe.vmoptions
追加
-Dfile.encoding=utf-8
测试用例
onBnPressed(): void {
this.testFileIO();
}
async testFileIO() {
hilog.info(0x0001, "mylog", "[testFileIO] start");
let io = new FileIoTxt();
let root = await io.getExternalCacheDir();
hilog.info(0x0001, "mylog", "[testFileIO] root = " + root);
/**
* root = /storage/emulated/0/Android/data/com.xxxx.unittest_harmony_os_arkts/cache
*/
let dstFpne = root + "/" + "temp.txt";
let message = "哈哈\n";
message = message + "哈哈2\n";
await io.writeTxt(dstFpne, message);
let context = await io.readTxt(dstFpne);
hilog.info(0x0001, "mylog", "[testFileIO] txt = " + context);
hilog.info(0x0001, "mylog", "[testFileIO] finished");
}
TXT文件读写类封装
file_io_txt.ets
import util from '@ohos.util';
import fileio from '@ohos.fileio';
import hilog from '@ohos.hilog';
import featureAbility from '@ohos.ability.featureAbility';
export class FileIoTxt {
constructor() {
}
public async getExternalCacheDir(): Promise<string> {
let context = featureAbility.getContext();
let root = await context.getExternalCacheDir();
return root;
}
public async writeTxt(fpne: string, msg: string) {
hilog.info(0x0001, "mylog", "[writeTxt] start");
let fd = await fileio.open(fpne, 0o100 | 0o2, 0o666);
try {
let number = await fileio.write(fd, msg);
hilog.info(0x0001, "mylog", "[writeTxt] write size = " + number);
} catch (error) {
hilog.info(0x0001, "mylog", "[writeTxt] error = " + error);
}
hilog.info(0x0001, "mylog", "[writeTxt] finished to " + fpne);
}
public async readTxt(fpne: string): Promise<string> {
hilog.info(0x0001, "mylog", "[readTxt] start");
let fd = await fileio.open(fpne, 0o2);
let buf = new ArrayBuffer(4096);
let ret: string;
try {
let readOut = await fileio.read(fd, buf);
let decoder = new util.TextDecoder("utf-8", { ignoreBOM: true });
ret = decoder.decode(new Uint8Array(readOut.buffer), { stream: false });
} catch (err) {
hilog.info(0x0001, "mylog", "[readTxt] err: " + err);
}
hilog.info(0x0001, "mylog", "[readTxt] finished = " + ret);
return ret;
}
}
LOG输出
: [testFileIO] start
: [testFileIO] root = /storage/emulated/0/Android/data/com.xxxx.unittest_harmony_os_arkts/cache
: [writeTxt] start
: [writeTxt] write size = 15
: [writeTxt] finished to /storage/emulated/0/Android/data/com.xxxx.unittest_harmony_os_arkts/cache/temp.txt
: [readTxt] start
: [readTxt] finished = 哈哈
: 哈哈2
: [testFileIO] txt = 哈哈
: 哈哈2
: [testFileIO] finished
更多关于 HarmonyOS 鸿蒙Next TXT文件读写 中文乱码的实战教程也可以访问 https://www.itying.com/category-93-b0.html
1 回复