# FileSystemManager.readFile

读取本地文件内容。

# 支持说明

应用能力 Android iOS PC 预览效果
小程序 3.12.0 3.11.0 3.10.0
扫码预览
用BoosHi扫码或PC端点击
网页应用 待开发 待开发 待开发 待补充

# 输入

继承标准对象输入,扩展属性:

名称 数据类型 必填 默认值 描述
filePath string 要读取的本地文件路径
示例值:bzfile://temp/test.jpg
encoding string 指定读取文件的字符编码,如果不传 encoding,则以 ArrayBuffer 格式读取文件的二进制内容
position number 0 从文件指定位置开始读,如果不指定,则从文件头开始读。读取的范围应该是左闭右开区间 [position, position+length)。有效范围:[0, fileLength - 1]。单位:byte。
示例值:5
length number 指定读取的长度,如果不指定,则读到文件末尾,如果可读长度小于指定长度,则返回可读长度。有效范围:[0, fileLength]。单位:byte。
示例值:10
单次读取最大:10 * 1024 * 1024

# encoding 的合法值

说明 Android iOS PC
ascii 支持 支持 不支持
base64 支持 支持 支持
binary 支持 支持 不支持
hex 支持 支持 支持
ucs2/ucs-2/utf16le/utf-16le 以小端序读取 支持 支持 不支持
utf-8/utf8 支持 支持 支持
latin1 支持 支持 不支持

# 输出

继承标准对象输出success返回对象的扩展属性:

名称 数据类型 描述
data string ArrayBuffer

# 示例代码

const fileSystemManager = bz.getFileSystemManager();
fileSystemManager.readFile({
    filePath: "bzfile://temp/test.jpg",
    encoding: "base64",
    position: 5,
    length: 10,
    success(res) {
      console.log(res);
    },
    fail(res) {
      console.log(`readFile fail: ${JSON.stringify(res)}`);
    }
});
1
2
3
4
5
6
7
8
9
10
11
12
13

success返回对象示例:

  • data 为 string 类型
{
  data: 'EEpGSUYAAQEAAA==',
  errMsg: 'readFile:ok'
}
1
2
3
4
  • data 为 arraybuffer 类型
{
  errMsg: 'readFile:ok',
  data: ArrayBuffer(10)
}
1
2
3
4

# 分片读取示例

function readFileBySlice(path, position, total, slice, uint8Buffer, callback) {
    if (position >= total) {
        callback(uint8Buffer)
        return
    }
    if (slice > 1024 * 1024) {
        slice = 1024 * 1024 // 建议每一片不要超过1M,否则可能引起性能问题
    }
    bz.getFileSystemManager().readFile({
        filePath: path,
        position: position,
        length: slice < total ? slice : total,
        success(res) {
            // 输出读取的文件内容
            const srcUint8 = new Uint8Array(res.data)
            uint8Buffer.set(srcUint8, position)
            const nextPosition = position + srcUint8.buffer.byteLength;
            readFileBySlice(path, nextPosition, total, slice, uint8Buffer, callback)
        },
        fail(res) {
            console.log("调用失败", res.errMsg);
        }
    });
}

const slice = 1024 * 1024 // 1M
const filePath = "your file path";
const fileSize = "your file size";
const uint8Buffer = new Uint8Array(new ArrayBuffer(fileSize))
readFileBySlice(filePath, 0, fileSize, slice, uint8Buffer, (uint8Buffer) => {
  //todo
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
最后更新于 : 5/18/2023, 3:09:13 PM