目录

Accessing Application Files

This topic describes how to enable an application to view, create, read, write, delete, or copy an application file and obtain file information.

Available APIs

You can use basic file operation APIs (ohos.file.fs) to access application files. The main functions are listed in the following table.

Table 1 APIs for basic application file operations

Name Function API Type Sync Async
access Checks whether a file exists. Method √ √
close Closes a file. Method √ √
copyFile Copies a file. Method √ √
listFile Lists all files in a directory. Method √ √
mkdir Creates a directory. Method √ √
open Opens a file. Method √ √
read Reads data from a file. Method √ √
rename Renames a file or folder. Method √ √
rmdir Removes a directory. Method √ √
stat Obtains detailed file information. Method √ √
unlink Deletes a single file. Method √ √
write Writes data to a file. Method √ √
File.fd Obtains a file descriptor. Property - -
OpenMode Sets the file open mode. Property - -
Filter Sets file filtering options. Type - -

How to Develop

Before accessing an application file, you need to obtain the application file path. The following example describes how to obtain the HAP-level file path from UIAbilityContext. For details about how to obtain UIAbilityContext, see Obtaining the Context of UIAbility.

The following walks you through common operations.

[h2]Creating, Reading, and Writing a File

The following example demonstrates how to create a file, read data from it, and write data to it.

// pages/xxx.ets
import { fileIo } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { buffer } from '@kit.ArkTS';

// To obtain the application file path, you need to obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;

function createFile(context: common.UIAbilityContext): void {
  let filesDir = context.filesDir;
  // Create a file and open it.
  let file = fileIo.openSync(filesDir + '/test.txt', fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
  // Write data to the file.
  let writeLen = fileIo.writeSync(file.fd, "Try to write str.");
  console.info("The length of str is: " + writeLen);
  // Read data from the file.
  let arrayBuffer = new ArrayBuffer(1024);
  class Option {
    public offset: number = 0;
    public length: number = 0;
  }
  let option = new Option();
  option.length = arrayBuffer.byteLength;
  let readLen = fileIo.readSync(file.fd, arrayBuffer, option);
  let buf = buffer.from(arrayBuffer, 0, readLen);
  console.info("the content of file: " + buf.toString());
  // Close the file.
  fileIo.closeSync(file);
}

[h2]Creating, Reading, and Writing a GBK File

The following example demonstrates how to create a file, read data from it, and write data to it.

// pages/xxx.ets
import { fileIo } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { buffer } from '@kit.ArkTS';
import { util } from '@kit.ArkTS';

// To obtain the application file path, you need to obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
// Convert the file encoding format.
export function StringToBuffer(content: string) {
    let textEncoder = new util.TextEncoder("gbk");
    let resultBuf = textEncoder.encodeInto(content);
    return resultBuf;
}

function createFile(context: common.UIAbilityContext): void {
  let filesDir = context.filesDir;
  // Create a file and open it.
  let file = fileIo.openSync(filesDir + '/test.txt', fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
  // Write data to the file.
  
  let writeLen = fileIo.writeSync(file.fd, StringToBuffer("Try to write str.").buffer);
  console.info("The length of str is: " + writeLen);
  // Read data from the file.
  let arrayBuffer = new ArrayBuffer(1024);
  class Option {
    public offset: number = 0;
    public length: number = 0;
  }
  let option = new Option();
  option.length = arrayBuffer.byteLength;
  let readLen = fileIo.readSync(file.fd, arrayBuffer, option);
  let buf = buffer.from(arrayBuffer, 0, readLen);
  console.info("the content of file: " + buf.toString());
  // Close the file.
  fileIo.closeSync(file);
}

[h2]Copying Data to Another File

The following example demonstrates how to read data from a file and copy it to another file.

// pages/xxx.ets
import { fileIo } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';

// To obtain the application file path, you need to obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;

function readWriteFile(context: common.UIAbilityContext): void {
  let filesDir = context.filesDir;
  // Open a file.
  let srcFile = fileIo.openSync(filesDir + '/test.txt', fileIo.OpenMode.READ_WRITE);
  let destFile = fileIo.openSync(filesDir + '/destFile.txt', fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
  // Read data from the source file and copy it to the destination file.
  let bufSize = 4096;
  let readSize = 0;
  let buf = new ArrayBuffer(bufSize);
  class Option {
    public offset: number = 0;
    public length: number = bufSize;
  }
  let option = new Option();
  option.offset = readSize;
  let readLen = fileIo.readSync(srcFile.fd, buf, option);
  while (readLen > 0) {
    readSize += readLen;
    fileIo.writeSync(destFile.fd, buf);
    option.offset = readSize;
    readLen = fileIo.readSync(srcFile.fd, buf, option);
  }
  // Close the file.
  fileIo.closeSync(srcFile);
  fileIo.closeSync(destFile);
}

When using read() or write(), pay attention to the optional parameter offset. For a file that has been read or written, offset points to the end position of the last read or write operation by default.

[h2]Obtaining Files

The following example demonstrates how to obtain files that meet the specified conditions.

import { fileIo, Filter } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';

// To obtain the application file path, you need to obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext

// Obtain files that meet the specified conditions.
function getListFile(context: common.UIAbilityContext): void {
  class ListFileOption {
    public recursion: boolean = false;
    public listNum: number = 0;
    public filter: Filter = {};
  }
  let option = new ListFileOption();
  option.filter.suffix = ['.png', '.jpg', '.txt'];          // The file name extension can be '.png', '.jpg', or '.txt'.
  option.filter.displayName = ['test*'];                    // The file name starts with 'test'.
  option.filter.fileSizeOver = 0;                           // The size of the matched file is greater than 0.
  option.filter.lastModifiedAfter = new Date(0).getTime();  // The latest modification time of the file is later than January 1, 1970.
  let filesDir = context.filesDir;
  let files = fileIo.listFileSync(filesDir, option);
  for (let i = 0; i < files.length; i++) {
    console.info(`The name of file: ${files[i]}`);
  }
}