HarmonyOS如何获取“文件管理”App的 Documents 目录的路径?

应用下载文件到 cacheDir 目录后,想将下载后的文件转存到“文件管理”App的 Documents 目录中,如何获取这个目录的路径,是否需要请求权限,能给出一个完整转存流程的代码最好。

阅读 685
1 个回答

请参考下面的demo:

import fs from '@ohos.file.fs';
import { common } from '@kit.AbilityKit';
import { picker } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  private appContext: common.Context = getContext(this);
  private fileDir: string = ''
  createFile(){
    let cacheDir = this.appContext.cacheDir;
    this.fileDir = cacheDir + '/HelloWorld.txt'
    let file = fs.openSync(this.fileDir, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
    let writeLen = fs.writeSync(file.fd, 'hello world!');
    console.info("write data to file succeed and size is:" + writeLen);
    fs.closeSync(file)
  }
  saveFile(){
    try {
      let documentSaveOptions = new picker.DocumentSaveOptions();
      documentSaveOptions.newFileNames = ['HelloWorld.txt'];
      let documentPicker = new picker.DocumentViewPicker();
      documentPicker.save(documentSaveOptions).then((documentSaveResult: Array<string>) => {
        let uri = documentSaveResult[0];
        let sanFile = fs.openSync(this.fileDir, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
        let pubFile = fs.openSync(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
        fs.copyFileSync(sanFile.fd, pubFile.fd)
        fs.close(sanFile)
        fs.close(pubFile)
        console.info('DocumentViewPicker.save successfully, documentSaveResult uri: ' + JSON.stringify(documentSaveResult));
      }).catch((err: BusinessError) => {
        console.error('DocumentViewPicker.save failed with err: ' + JSON.stringify(err));
      });
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error('DocumentViewPicker failed with err: ' + JSON.stringify(err));
    }
  }
  build() {
    Row() {
      Column() {
        Button(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(()=>{
            this.createFile();
            this.saveFile();
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进