在KaihongOS中,可以使用文件管理对文件进行基础的操作 - KaihongOS技术社区 - 电子技术论坛 - 广受欢迎的专业电子论坛
分享 收藏 返回
王飞云 关注 私信
[文章]

在KaihongOS中,可以使用文件管理对文件进行基础的操作

文件操作

在KaihongOS中,可以使用@ohos.file.fs (文件管理)对文件进行基础的操作。下面简单介绍一下关于本地文件的查询、拷贝、删除、修改的操作。
导入模块
import fs from '@ohos.file.fs';使用说明使用该功能模块对文件/目录进行操作前,需要先获取其应用沙箱路径,获取方式及其接口用法请参考:
import UIAbility from '@ohos.app.ability.UIAbility';import window from '@ohos.window';export default class EntryAbility extends UIAbility {  onWindowStageCreate(windowStage: window.WindowStage) {    let context = this.context;    let pathDir = context.filesDir;  }}使用该功能模块对文件/目录进行操作前,需要先获取其应用沙箱路径,获取方式及其接口用法请参考:应用上下文Context-获取应用文件路径
本地文件查询

在KaihongOS中,查询的能力可以分为查询指定目录下的所有文件名以及读取指定文件的内容,
fs.listFile

listFile(path: string, options?: ListFileOptions): Promise
列出文件夹下所有文件名,支持递归列出所有文件名(包含子目录下),支持文件过滤,使用Promise异步返回。
系统能力:SystemCapability.FileManagement.File.FileIO
参数:
参数名类型必填说明
pathstring文件夹的应用沙箱路径。
optionsListFileOptions文件过滤选项。默认不进行过滤。
返回值:
类型说明
PromisePromise对象。返回文件名数组。
示例:
import { BusinessError } from '@ohos.base';import fs, { Filter } from '@ohos.file.fs';class ListFileOption {  public recursion: boolean = false;  public listNum: number = 0;  public filter: Filter = {};}let option = new ListFileOption();option.filter.suffix = [".png", ".jpg", ".jpeg"];option.filter.displayName = ["*abc", "efg*"];option.filter.fileSizeOver = 1024;option.filter.lastModifiedAfter = new Date().getTime();fs.listFile(pathDir, option).then((filenames: Array) => {  console.info("listFile succeed");  for (let i = 0; i < filenames.length; i++) {    console.info("fileName: %s", filenames);  }}).catch((err: BusinessError) => {  console.error("list file failed with error message: " + err.message + ", error code: " + err.code);});fs.read

read(fd: number, buffer: ArrayBuffer, options?: ReadOptions): Promise
从文件读取数据,使用Promise异步返回。
系统能力:SystemCapability.FileManagement.File.FileIO
参数:
参数名类型必填说明
fdnumber已打开的文件描述符。
bufferArrayBuffer用于保存读取到的文件数据的缓冲区。
optionsReadOptions支持如下选项:
- offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读。
- length,number类型,表示期望读取数据的长度。可选,默认缓冲区长度。
返回值:
类型说明
PromisePromise对象。返回读取的实际数据长度。
示例:
import { BusinessError } from '@ohos.base';import buffer from '@ohos.buffer';let filePath = pathDir + "/test.txt";let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE);let arrayBuffer = new ArrayBuffer(4096);fs.read(file.fd, arrayBuffer).then((readLen: number) => {  console.info("read file data succeed");  let buf = buffer.from(arrayBuffer, 0, readLen);  console.info(`The content of file: ${buf.toString()}`);}).catch((err: BusinessError) => {  console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);}).finally(() => {  fs.closeSync(file);});fs.readText

readText(filePath: string, options?: ReadTextOptions): Promise
基于文本方式读取文件(即直接读取文件的文本内容),使用Promise异步返回。
系统能力:SystemCapability.FileManagement.File.FileIO
参数:
参数名类型必填说明
filePathstring文件的应用沙箱路径。
optionsReadTextOptions支持如下选项:
- offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读取。
- length,number类型,表示期望读取数据的长度。可选,默认文件长度。
- encoding,string类型,当数据是 string 类型时有效,表示数据的编码方式,默认 ‘utf-8’,仅支持 ‘utf-8’。
返回值:
类型说明
PromisePromise对象。返回读取文件的内容。
示例:
import { BusinessError } from '@ohos.base';let filePath = pathDir + "/test.txt";fs.readText(filePath).then((str: string) => {  console.info("readText succeed:" + str);}).catch((err: BusinessError) => {  console.error("readText failed with error message: " + err.message + ", error code: " + err.code);});本地文件拷贝

在KaihongOS中,拷贝的能力可以分为文件的拷贝和文件夹的拷贝。
fs.copyFile

copyFile(src: string | number, dest: string | number, mode?: number): Promise
复制文件,使用Promise异步返回。
系统能力:SystemCapability.FileManagement.File.FileIO
参数:
参数名类型必填说明
srcstring | number待复制文件的路径或待复制文件的文件描述符。
deststring | number目标文件路径或目标文件的文件描述符。
modenumbermode提供覆盖文件的选项,当前仅支持0,且默认为0。
0:完全覆盖目标文件,未覆盖部分将被裁切掉。
返回值:
类型说明
PromisePromise对象。无返回值。
示例:
import { BusinessError } from '@ohos.base';let srcPath = pathDir + "/srcDir/test.txt";let dstPath = pathDir + "/dstDir/test.txt";fs.copyFile(srcPath, dstPath, 0).then(() => {  console.info("copy file succeed");}).catch((err: BusinessError) => {  console.error("copy file failed with error message: " + err.message + ", error code: " + err.code);});fs.copyDir10+

copyDir(src: string, dest: string, mode?: number): Promise
复制源文件夹至目标路径下,使用Promise异步返回。
系统能力:SystemCapability.FileManagement.File.FileIO
参数:
参数名类型必填说明
srcstring源文件夹的应用沙箱路径。
deststring目标文件夹的应用沙箱路径。
modenumber复制模式。默认mode为0。
-  mode为0,文件级别抛异常。目标文件夹下存在与源文件夹名冲突的文件夹,若冲突文件夹下存在同名文件,则抛出异常。源文件夹下未冲突的文件全部移动至目标文件夹下,目标文件夹下未冲突文件将继续保留,且冲突文件信息将在抛出异常的data属性中以Array<ConflictFiles>形式提供。
-  mode为1,文件级别强制覆盖。目标文件夹下存在与源文件夹名冲突的文件夹,若冲突文件夹下存在同名文件,则强制覆盖冲突文件夹下所有同名文件,未冲突文件将继续保留。
返回值:
类型说明
PromisePromise对象。无返回值。
示例:
import { BusinessError } from '@ohos.base';// copy directory from srcPath to destPathlet srcPath = pathDir + "/srcDir/";let destPath = pathDir + "/destDir/";fs.copyDir(srcPath, destPath, 0).then(() => {  console.info("copy directory succeed");}).catch((err: BusinessError) => {  console.error("copy directory failed with error message: " + err.message + ", error code: " + err.code);});本地文件删除

在KaihongOS中,删除的能力可以分为文件的删除和文件夹的删除。
fs.unlink

unlink(path: string): Promise
删除单个文件,使用Promise异步返回。
系统能力:SystemCapability.FileManagement.File.FileIO
参数:
参数名类型必填说明
pathstring文件的应用沙箱路径。
返回值:
类型说明
PromisePromise对象。无返回值。
示例:
import { BusinessError } from '@ohos.base';let filePath = pathDir + "/test.txt";fs.unlink(filePath).then(() => {  console.info("remove file succeed");}).catch((err: BusinessError) => {  console.error("remove file failed with error message: " + err.message + ", error code: " + err.code);});fs.rmdir

rmdir(path: string): Promise
删除整个目录,使用Promise异步返回。
系统能力:SystemCapability.FileManagement.File.FileIO
参数:
参数名类型必填说明
pathstring目录的应用沙箱路径。
返回值:
[tr]类型说明[/tr]
PromisePromise对象。无返回值。
示例:
import { BusinessError } from '@ohos.base';let dirPath = pathDir + "/testDir";fs.rmdir(dirPath).then(() => {  console.info("rmdir succeed");}).catch((err: BusinessError) => {  console.error("rmdir failed with error message: " + err.message + ", error code: " + err.code);});本地文件修改

在KaihongOS中,对于文件的修改需要先读取文件内容,再手动修改后重新写入(此时若文件过大,可能需要将原文件删除后再新建并写入)。
fs.write

write(fd: number, buffer: ArrayBuffer | string, options?: WriteOptions): Promise
将数据写入文件,使用Promise异步返回。
系统能力:SystemCapability.FileManagement.File.FileIO
参数:
参数名类型必填说明
fdnumber已打开的文件描述符。
bufferArrayBuffer | string待写入文件的数据,可来自缓冲区或字符串。
optionsWriteOptions支持如下选项:
- offset,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写。
- length,number类型,表示期望写入数据的长度。可选,默认缓冲区长度。
- encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 ‘utf-8’。当前仅支持 ‘utf-8’。
返回值:
类型说明
PromisePromise对象。返回实际写入的数据长度,单位字节。
示例:
import { BusinessError } from '@ohos.base';let filePath = pathDir + "/test.txt";let str: string = fs.readText(filePath)let newStr: string = "hello, world!" + str;let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);fs.write(file.fd, newStr).then((writeLen: number) => {  console.info("write data to file succeed and size is:" + writeLen);}).catch((err: BusinessError) => {  console.error("write data to file failed with error message: " + err.message + ", error code: " + err.code);}).finally(() => {  fs.closeSync(file);});

更多回帖

×