HarmonyOS 解压中文文件名的压缩包时文件名乱码?

zlib.decompressFile(inFile, outFileDir, options).then(() =\>{ })使用该接口解压应用沙箱内的中文名的压缩包会导致解压出来的文件夹名称是乱码,且无法打开。如何设置可以正常解压中文名zip压缩包?以下是完整实现方法:

async onWindowStageCreate(windowStage: window.WindowStage) {
  // Main window is created, set main page for this ability
  hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
  let rawfile: Uint8Array;
  //1.读rawfile
  rawfile = this.context.resourceManager.getRawFileContentSync("测试文件夹.zip")
  //2.获取沙箱目录
  let context = this.context;
  let pathDir = context.filesDir;
  console.log('testRawfile---沙箱路径' + pathDir);
  //3.使用file.write接口将字节数组形式的rawfile的文件写入到沙箱目录中
  let filePath = pathDir + "/测试文件夹.zip";
  let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  let rawFileBuffer = rawfile.buffer; //类型转换
  let writeLen = fs.writeSync(file.fd, rawFileBuffer)
  console.info("testRawfile--write data to file succeed and size is:" + writeLen);
  fs.fdatasync(file.fd)
  fs.closeSync(file);

  await testDecompress(filePath,pathDir)

  windowStage.loadContent('pages/Index', (err) => {
    if (err.code) {
      hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
      return;
    }
    hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');
  });
}
async function testDecompress(inFile:string,outFileDir:string) {
  //4.解压
  let options: zlib.Options = {
    level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION
  };
  await zlib.decompressFile(inFile, outFileDir, options).then(() => {
    console.log('testrawfile--decompress')
  })
}
阅读 664
1 个回答

解压后乱码根因是文件夹在压缩时是windows默认的编码格式,与ArkTS中的zlib.decompress解码方式不配套,导致文件夹名乱码。

1、采用ArkTS一套压缩和解压方式,如zlib.compress压缩和zlib.decompress解压。

2、可先采用如7zip等软件设置压缩参数cu=on,即可防止中文名乱码的情况。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进