概要
本地json存放位置以及读取json文件
json文件存放位置
图片存在rawfile中
读取rawfile文件,并将其转为string
import { BusinessError } from '@kit.BasicServicesKit';
import { util } from '@kit.ArkTS';
try {
getContext().resourceManager.getRawFileContent("文件名.json").then((value : Uint8Array) =>{
// let rawfile = value
// 将 Uint8Array 转换为字符串
let file_data : String = uint8ArrayToString(value)
console.log("chess_data---",JSON.stringify(file_data))
}).catch((error : BusinessError) =>{
console.error("getRawFileContent promise error is " + error);
})
} catch (e) {
console.error("error is "+(e as BusinessError).message);
}
// 字节流转成可理解的字符串
function uint8ArrayToString(array: Uint8Array) {
let textDecoderOptions: util.TextDecoderOptions = {
fatal: false,
ignoreBOM: true
}
let decodeToStringOptions: util.DecodeToStringOptions = {
stream: false
}
let textDecoder = util.TextDecoder.create('utf-8', textDecoderOptions);
let retStr = textDecoder.decodeToString(array, decodeToStringOptions);
console.info('字节流转成可理解的字符串:' + retStr);
return retStr;
}
其他相关方法
import { buffer, util } from '@kit.ArkTS';
// 字符串转成字节流
function stringToUint8Array(str: string) {
console.info('字符串转成字节流:' + new Uint8Array(buffer.from(str, 'utf-8').buffer));
return new Uint8Array(buffer.from(str, 'utf-8').buffer);
}
// 字节流转成可理解的字符串
function uint8ArrayToString(array: Uint8Array) {
let textDecoderOptions: util.TextDecoderOptions = {
fatal: false,
ignoreBOM: true
}
let decodeToStringOptions: util.DecodeToStringOptions = {
stream: false
}
let textDecoder = util.TextDecoder.create('utf-8', textDecoderOptions);
let retStr = textDecoder.decodeToString(array, decodeToStringOptions);
console.info('字节流转成可理解的字符串:' + retStr);
return retStr;
}
//十六进制转Uint8Array
function HexStrTouint8Array(data: string): Uint8Array {
console.info('十六进制转Uint8Array:' + new Uint8Array(buffer.from(data, 'hex').buffer));
return new Uint8Array(buffer.from(data, 'hex').buffer);
}
// Uint8Array转十六进制
function uint8ArrayToHexStr(data: Uint8Array): string {
let hexString = '';
let i: number;
for (i = 0; i < data.length; i++) {
let char = ('00' + data[i].toString(16)).slice(-2);
hexString += char;
}
console.info('Uint8Array转十六进制:' + hexString);
return hexString;
}
let uint8Array: Uint8Array;
@Entry
@Component
struct TypeConversion {
build() {
Column({ space: 12 }) {
Button('字符串转成字节流')
.onClick(() => {
let str = 'hello';
uint8Array = stringToUint8Array(str);
})
Button('字节流转字符串')
.onClick(() => {
if (uint8Array) {
uint8ArrayToString(uint8Array);
}
})
Button('十六进制转Uint8Array')
.onClick(() => {
let data = '05160b22';
HexStrTouint8Array(data);
})
Button('Uint8Array转十六进制')
.onClick(() => {
let uint8Array = new Uint8Array([5, 22, 11, 34]);
uint8ArrayToHexStr(uint8Array);
})
}
.width('100%')
.justifyContent(FlexAlign.Center)
}
}