HarmonyOS鸿蒙Next中怎么打开应用内文件

HarmonyOS鸿蒙Next中怎么打开应用内文件 使用ArkTS,怎么根据文件类型打开对应的应用来查看文件呀?

类似安卓:

private void openFile(File file) {
    let intent = new Intent();
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setAction(android.content.Intent.ACTION_VIEW);
    let type = getMIMEType(file);
    intent.setDataAndType(Uri.fromFile(file), type);
    startActivity(intent);
}
6 回复

在HOS 里, UIAbility类似安卓的Activity, 一个UIAbility(caller)要调用外部的UIAbility(callee)执行进一步的操作, 首先有对相应的UIAbility(callee)进行配置, 当caller调用callee时,要传递相关的参数(包括 要匹配的 callee的参数, 也包含操作对象的参数)。

下面的连接有具体的解释:

https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/want-overview-0000001478340877-V3

更多关于HarmonyOS鸿蒙Next中怎么打开应用内文件的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


根据文档写了个方法:

export function openFile(path: string, contentType: string) {
  let uri = fileuri.getUriFromPath(path);
  let want = {
    action: "ohos.want.action.viewData",
    uri: uri,
    type: contentType
  }
  let context = getContext(this) as common.UIAbilityContext;
  context.startAbility(want)
    .then(() => {
      console.info('Invoke getCurrentBundleStats succeeded.');
    })
    .catch((err) => {
      console.error(`Invoke startAbility failed, code is ${err.code}, message is ${err.message}`);
    });
}

代码会走到then里边,但是会退到桌面,然后6s之后没响应就挂了:


STRINGID:THREAD_BLOCK_6SApp  
MSG:App main thread is not response! EventHandler dump begain curTime:20240126 10:35 AM

在什么调试环境下调试的呢?

api9,真机:P50HarmonyOS 4.0.0

在HarmonyOS鸿蒙Next中,打开应用内文件可以通过使用FileFilePath类来实现。首先,确保应用已经获取了文件路径。可以使用getFilesDir()方法获取应用内部存储的文件目录。

import file from '@ohos.file';
import filePath from '@ohos.file.path';

// 获取应用内部存储的文件目录
let internalDir = file.getFilesDir();

// 拼接文件路径
let filePath = filePath.join(internalDir, 'example.txt');

// 打开文件
file.open(filePath, file.OpenMode.READ_ONLY).then((fd) => {
    // 读取文件内容
    file.read(fd, new ArrayBuffer(1024), { offset: 0, length: 1024 }).then((readOut) => {
        console.log(`File content: ${new TextDecoder().decode(readOut.buffer)}`);
        // 关闭文件
        file.close(fd);
    });
}).catch((err) => {
    console.error(`Failed to open file: ${err.message}`);
});

在上述代码中,首先获取应用内部存储的文件目录,然后拼接文件路径。使用file.open()方法打开文件,并通过file.read()方法读取文件内容。最后,使用file.close()方法关闭文件。

在HarmonyOS鸿蒙Next中,打开应用内文件可以通过以下步骤实现:

  1. 使用File API:通过ohos.file.fs模块的File类,可以访问应用内文件。例如,使用openSync方法打开文件,然后进行读写操作。

  2. 文件路径:应用内文件通常存储在/data/data/<包名>/files/目录下。可以通过context.getFilesDir()获取该路径。

  3. 示例代码

    const filePath = context.getFilesDir() + '/example.txt';
    const file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
    const content = fs.readSync(file.fd, new ArrayBuffer(1024));
    console.log(String.fromCharCode.apply(null, new Uint8Array(content)));
    fs.closeSync(file.fd);
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!