目录

How do I convert the content in a file into strings?

  1. Obtain the target file in the resources/rawfile directory.
  2. Call TextDecoder of the util module to decode byte arrays of the file into strings.
  3. Decode Uint8 arrays.

The code snippet is as follows:

import { util } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct FileToString {
  build() {
    Row() {
      Column() {
        Button('file to string')
          .onClick(() => {
            getContext().resourceManager.getRawFileContent('test.txt').then((value: Uint8Array) => {
              let textDecoder: util.TextDecoder = util.TextDecoder.create(); // Call the TextDecoder class of the til module
              let decodedString: string = textDecoder.decodeToString(value); // Decode the Uint8Array.
              let strBase64 = new util.Base64Helper().encodeToStringSync(value); // Convert a Uint8Array to a Base64 string
              console.info('retStr:', decodedString);
              console.info('strBase64:', strBase64);
            }).catch((error: BusinessError) => {
              console.error(`callback getRawFileContent failed, error code: ${error.code}, message: ${error.message}.`);
            });
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

Reference

getRawFileContent

TextDecoder