File 模块
android.file 负责设备端文件与目录操作,适合日志、配置、截图文件和中间产物管理。除基础文件读写外,当前也提供下载任务能力:先创建任务拿到 downloadId,再轮询状态,必要时主动取消。
常用方法
writeBase64(filePath, base64Content)
把 Base64 字符串写入文件。
- 参数:
filePath: stringbase64Content: string
- 返回值:
Promise<boolean>
writeStr(filePath, textContent, append)
写入文本内容。
- 参数:
filePath: stringtextContent: stringappend: boolean:true追加,false覆盖
- 返回值:
Promise<boolean>
await android.file.writeStr('/data/local/tmp/demo.txt', 'hello accbot', false)readStr(filePath)
读取文本内容。
- 参数:
filePath: string - 返回值:
Promise<string>
readFileToBase64(filePath)
读取文件并转为 Base64。
- 参数:
filePath: string - 返回值:
Promise<string>
createDir(dirPath)
创建目录。
- 参数:
dirPath: string - 返回值:
Promise<boolean>
createFile(filePath)
创建文件。
- 参数:
filePath: string - 返回值:
Promise<boolean>
getFileInfo(filePath)
获取文件信息。
- 参数:
filePath: string - 返回值:文件信息对象
getDirInfo(dirPath)
获取目录信息。
- 参数:
dirPath: string - 返回值:目录信息对象
copyFile(src, dest)
复制文件。
- 参数:
src: stringdest: string
- 返回值:
Promise<boolean>
rename(src, dest)
重命名文件或目录。
delFile(filePath)
删除文件。
delDir(dirPath)
删除目录。
downloadFile(fileURL, savePath)
同步下载文件。
- 参数:
fileURL: stringsavePath: string
- 返回值:
Promise<boolean>
asyncDownloadFile(fileURL, savePath, headers?, cookies?)
创建异步下载任务并返回 downloadId。
- 参数:
fileURL: stringsavePath: stringheaders?: Record<string, string>cookies?: Record<string, string>
- 返回值:
Promise<number>
DownloadFileWithProgress(fileURL, savePath, headers?, cookies?)
创建下载任务并返回 downloadId。
- 说明:该方法名保留历史命名,但当前契约不会主动推送进度,也不再依赖
push.downloadChange - 参数:
fileURL: stringsavePath: stringheaders?: Record<string, string>cookies?: Record<string, string>
- 返回值:
Promise<number>
getDownloadTaskStatus(downloadId)
查询下载任务状态。
- 参数:
downloadId: number - 返回值:
Promise<{ downloadId, status, progress, savePath, errorMsg }> - 状态常量中文语义:
100:等待中101:下载中200:已完成-1:失败-2:已取消
cancelDownloadTask(downloadId)
取消下载任务。
- 参数:
downloadId: number - 返回值:
Promise<{ success: boolean }>
const downloadId = await android.file.DownloadFileWithProgress(
'https://speed.cloudflare.com/__down?bytes=1024',
'/data/local/tmp/demo.bin',
)
const status = await android.file.getDownloadTaskStatus(downloadId)
if (status.status === 100 || status.status === 101) {
console.log('任务仍在执行中', status.progress)
}下载任务建议调用顺序
- 调
DownloadFileWithProgress(...)或asyncDownloadFile(...)创建任务,拿到downloadId - 用
getDownloadTaskStatus(downloadId)轮询状态和进度 - 需要中止时调用
cancelDownloadTask(downloadId) - 当状态为
200时表示已完成;当状态为-1或-2时表示任务已结束且不可恢复
注意事项
- 调用前先确认
android.auth.openAllFile(false)为true - 尽量使用绝对路径,避免业务代码依赖当前工作目录
- 删除与覆盖类操作建议先记录日志,避免误删
