HarmonyOS鸿蒙Next中如何获取沙箱cache目录下的所有图片

HarmonyOS鸿蒙Next中如何获取沙箱cache目录下的所有图片 如何获取沙箱cache目录下的所有图片

4 回复

参考示例:

import { filePreview } from '@kit.PreviewKit';
import { BusinessError } from '@kit.BasicServicesKit';
import fs from '@ohos.file.fs';
import { hilog } from '@kit.PerformanceAnalysisKit';

let TAG = 'FileOpenedFromSandbox'
let uiContext = getContext(this);
let displayInfo: filePreview.DisplayInfo = {
  x: 100,
  y: 100,
  width: 800,
  height: 800
};
let fileInfo: filePreview.PreviewInfo = {
  title: 'th.jpg',
  uri: 'file://com.example.fileopenedfromsandbox/data/storage/el2/base/haps/entry/files/th.jpeg',
  mimeType: 'image/jpeg'
};

@Entry
@Component
struct Index11 {
  build() {
    Column() {
      Row() {
        Button('复制')
          .onClick(() => {
            let context = getContext(this);
            context.resourceManager.getRawFileContent("th.jpeg", (error: BusinessError, value: Uint8Array) => {
              if (error != null) {
                hilog.error(0xFFFF, TAG,"error is " + error);
              } else {
                let data = value.buffer;
                let filesDir = context.filesDir;
                let filePath = filesDir + '/th.jpeg'
                let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
                let writeLen = fs.writeSync(file.fd, data);
                hilog.info(0xFFFF, TAG,'testTag-write data to file succeed and size is:' + writeLen);
                fs.closeSync(file);
              }
            });

          })
      }
      .justifyContent(FlexAlign.SpaceAround)
      .width('100%')

      Row() {
        Button('预览')
          .onClick(() => {
            filePreview.openPreview(uiContext, fileInfo, displayInfo).then(() => {
              hilog.info(0xFFFF, TAG,'Succeeded in opening preview');
            }).catch((err: BusinessError) => {
              hilog.error(0xFFFF, TAG, `Failed to open preview, err.code = ${err.code}, err.message = ${err.message}`);
            });
          })
      }
      .justifyContent(FlexAlign.SpaceAround)
      .width('100%')
    }
    .justifyContent(FlexAlign.SpaceAround)
    .height('100%')
    .width('100%')
  }
}

更多关于HarmonyOS鸿蒙Next中如何获取沙箱cache目录下的所有图片的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


我沙箱文件里面有一堆时间戳命名得图片,这个该怎么拿到,

你好,可以参考示例遍历文件:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/app-file-access#查看文件列表。

在HarmonyOS鸿蒙Next中,获取沙箱cache目录下的所有图片可以通过以下步骤实现:

  1. 获取沙箱cache目录路径:使用Context.getCacheDir()方法获取应用的cache目录路径。
  2. 遍历目录:使用File类遍历cache目录下的所有文件。
  3. 筛选图片文件:通过文件扩展名(如.jpg, .png等)筛选出图片文件。

示例代码:

File cacheDir = getCacheDir();
File[] files = cacheDir.listFiles();
List<File> imageFiles = new ArrayList<>();
for (File file : files) {
    if (file.getName().endsWith(".jpg") || file.getName().endsWith(".png")) {
        imageFiles.add(file);
    }
}

此代码将返回cache目录下所有图片文件的列表。

回到顶部