脚本引擎 API

文件操作 API

runtime.files.* 读写设备存储文件。路径为绝对路径,支持文本/二进制读写、追加、删除、存在性检查、目录列出、文件元信息等。

当前:文件操作 API
脚本引擎 API

文件操作 API

runtime.files.* 读写设备存储文件。路径为绝对路径,支持文本/二进制读写、追加、删除、存在性检查、目录列出、文件元信息等。

概述

读写设备存储上的文件。路径必须为绝对路径,如 /sdcard/data/settings.json。文件写入自动创建父目录。支持文本和二进制(Base64 编码)两种读写模式。

方法列表

  • runtime.files.read(path): string — 读取文件全部文本内容。
  • runtime.files.write(path, content: string): void — 写入文本(自动创建父目录)。
  • runtime.files.append(path, content: string): void — 追加文本到文件末尾。
  • runtime.files.readBytes(path): string读取文件并返回 Base64 编码的字节数据
  • runtime.files.writeBytes(path, base64Data: string): boolean将 Base64 数据解码后写入文件(用于保存图片/二进制)。成功返回 true。
  • runtime.files.delete(path): boolean — 删除文件,成功返回 true。
  • runtime.files.exists(path): boolean — 文件是否存在。
  • runtime.files.listDir(path): string[] — 列出目录下的文件名数组。
  • runtime.files.size(path): number — 文件大小(字节)。
  • runtime.files.lastModified(path): number — 文件最后修改时间戳(毫秒)。
  • runtime.files.stat(path): object返回文件元信息对象,包含 sizelastModifiedexistsisDirectorycanReadcanWrite

调用示例

// 读取配置文件
var configPath = "/sdcard/config.json";
if (runtime.files.exists(configPath)) {
    var content = runtime.files.read(configPath);
    var config = JSON.parse(content);
    runtime.process.log("配置已加载: " + JSON.stringify(config));
} else {
    runtime.files.write(configPath, JSON.stringify({theme: "dark", lang: "zh"}));
}
// 下载图片并保存
var imgB64 = runtime.network.getBytes("https://example.com/img.png");
if (imgB64) {
    runtime.files.writeBytes("/sdcard/Download/img.png", imgB64);
    var info = runtime.files.stat("/sdcard/Download/img.png");
    runtime.process.log("文件大小: " + info.size + " 字节");
}
// 日志追加与目录列出
runtime.files.append("/sdcard/app.log", new Date().toISOString() + " - 任务执行\n");
var files = runtime.files.listDir("/sdcard/");
for (var i = 0; i < files.length; i++) {
    runtime.process.log("文件: " + files[i]);
}