We use essential cookies for the website to function, as well as analytics cookies for analyzing and creating statistics of the website performance. To agree to the use of analytics cookies, click "Accept All". You can manage your preferences at any time by clicking "Cookie Settings" on the footer. More Information.

Only Essential Cookies
Accept All
GuidesApplication FrameworkCore File KitApplication FilesApplication File Access and ManagementAccessing Application Files (ArkTS)

Accessing Application Files (ArkTS)

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

Available APIs

You can use ohos.file.fs to implement access to application files. The following table describes the commonly used APIs.

Table 1 Functions of ohos.file.fs APIs

Expand
API Description Category Synchronous Programming Asynchronous Programming
access Checks whether a file exists. Method Supported Supported
close Closes a file. Method Supported Supported
copyFile Copies a file. Method Supported Supported
createStream Creates a stream based on a file path. Method Supported Supported
listFile Lists all files in a directory. Method Supported Supported
mkdir Creates a directory. Method Supported Supported
moveFile Moves a file. Method Supported Supported
open Opens a file. Method Supported Supported
read Reads data from a file. Method Supported Supported
rename Renames a file or folder. Method Supported Supported
rmdir Removes a directory. Method Supported Supported
stat Obtains detailed file information. Method Supported Supported
unlink Deletes a single file. Method Supported Supported
write Writes data to a file. Method Supported Supported
Stream.close Closes a stream. Method Supported Supported
Stream.flush Flushes all data from this stream. Method Supported Supported
Stream.write Writes data to a stream. Method Supported Supported
Stream.read Reads data from a stream. Method Supported Supported
File.fd Obtains a file descriptor. Attribute N/A N/A
OpenMode Defines the mode for opening a file. Attribute N/A N/A
Filter Defines the options for filtering files. Type N/A N/A
NOTE

When using ohos.file.fs APIs, you are advised to use asynchronous APIs for time-consuming operations, such as read and write operations, to prevent application crashes.

Development Example

Before performing any file operation, obtain the application file path. The following example shows how to obtain a HAP file path using UIAbilityContext. For details about how to obtain UIAbilityContext, see Obtaining the Context of UIAbility.

The following walks you through on how to perform common file operations.

Creating, Reading, and Writing a File

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

Collapse
Word wrap
Dark theme
Copy code
  1. // pages/xxx.ets
  2. import { fileIo, ReadOptions } from '@kit.CoreFileKit';
  3. import { common } from '@kit.AbilityKit';
  4. import { buffer } from '@kit.ArkTS';
  5. // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
  6. let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
Collapse
Word wrap
Dark theme
Copy code
  1. function createFile(context: common.UIAbilityContext): void {
  2. let filesDir = context.filesDir;
  3. let file: fileIo.File | null = null;
  4. try {
  5. // Create and open the file if it does not exist, and open the file if it exists.
  6. file = fileIo.openSync(filesDir + '/test.txt', fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
  7. // Write a piece of content to the file.
  8. let writeLen = fileIo.writeSync(file.fd, 'Hello world');
  9. console.info('The length of str is: ' + writeLen);
  10. // Create an ArrayBuffer object of 1024 bytes to store data read from the file.
  11. let arrayBuffer = new ArrayBuffer(1024);
  12. // Set the read offset and length, in bytes.
  13. let readOptions: ReadOptions = {
  14. offset: 0,
  15. length: arrayBuffer.byteLength
  16. };
  17. // Read file content into the ArrayBuffer object and return the number of bytes actually read.
  18. let readLen = fileIo.readSync(file.fd, arrayBuffer, readOptions);
  19. // Convert the ArrayBuffer object to a Buffer object, and then convert it to a string for output.
  20. let buf = buffer.from(arrayBuffer, 0, readLen);
  21. console.info('Succeeded in creating file, the content of file: ' + buf.toString());
  22. } catch (err) {
  23. console.error(`Failed to create file. Code: ${err.code}, message: ${err.message}`);
  24. } finally {
  25. if (file) {
  26. try {
  27. fileIo.closeSync(file);
  28. } catch (err) {
  29. console.error(`Failed to close file`);
  30. }
  31. }
  32. }
  33. }

Copying Data to Another File

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

Collapse
Word wrap
Dark theme
Copy code
  1. // pages/xxx.ets
  2. import { fileIo, ReadOptions, WriteOptions } from '@kit.CoreFileKit';
  3. import { common } from '@kit.AbilityKit';
  4. // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
  5. let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
Collapse
Word wrap
Dark theme
Copy code
  1. function readWriteFile(context: common.UIAbilityContext): void {
  2. let srcFile: fileIo.File | null = null;
  3. let destFile: fileIo.File | null = null;
  4. try {
  5. let filesDir = context.filesDir;
  6. // Open the file in read/write mode. If the file does not exist, create it.
  7. srcFile = fileIo.openSync(filesDir + '/readFile.txt', fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
  8. destFile = fileIo.openSync(filesDir + '/writeFile.txt', fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
  9. // Create a buffer.
  10. let bufSize = 4096;
  11. let buf = new ArrayBuffer(bufSize);
  12. let readOffset = 0;
  13. let readLength = 128;
  14. // Set the read offset and length, in bytes.
  15. let readOptions: ReadOptions = {
  16. offset: readOffset,
  17. length: readLength
  18. };
  19. // Read the source file content in chunks and write it to the target file.
  20. let readLen = fileIo.readSync(srcFile.fd, buf, readOptions);
  21. while (readLen > 0) {
  22. readOffset += readLen;
  23. let writeOptions: WriteOptions = {
  24. length: readLen
  25. };
  26. // Write to the target file.
  27. fileIo.writeSync(destFile.fd, buf, writeOptions);
  28. // Update the read position.
  29. readOptions.offset = readOffset;
  30. readLen = fileIo.readSync(srcFile.fd, buf, readOptions);
  31. }
  32. console.info(`Succeeded in reading and writing file.`);
  33. } catch (err) {
  34. console.error(`Failed to read and write File. Code: ${err.code}, message: ${err.message}`);
  35. } finally {
  36. try {
  37. if (srcFile) {
  38. fileIo.closeSync(srcFile);
  39. }
  40. if (destFile) {
  41. fileIo.closeSync(destFile);
  42. }
  43. } catch (closeErr) {
  44. console.error(`Failed to close file`);
  45. }
  46. }
  47. }
NOTE

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.

Reading and Writing Files in a Stream

The following sample code shows how to use the stream() API to read the test.txt file content and write the content to the destFile.txt file.

Collapse
Word wrap
Dark theme
Copy code
  1. // pages/xxx.ets
  2. import { fileIo, ReadOptions } from '@kit.CoreFileKit';
  3. import { common } from '@kit.AbilityKit';
  4. // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
  5. let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
Collapse
Word wrap
Dark theme
Copy code
  1. async function readWriteFileWithStream(context: common.UIAbilityContext): Promise<void> {
  2. let filesDir = context.filesDir;
  3. let inputStream: fileIo.Stream | null = null;
  4. let outputStream: fileIo.Stream | null = null;
  5. try {
  6. // Create and open the input file stream.
  7. inputStream = fileIo.createStreamSync(filesDir + '/test.txt', 'r+');
  8. // Create and open the output file stream.
  9. outputStream = fileIo.createStreamSync(filesDir + '/destFile.txt', 'w+');
  10. let bufSize = 4096;
  11. let readSize = 0;
  12. let buf = new ArrayBuffer(bufSize);
  13. // Set the read offset and length, in bytes.
  14. let readOptions: ReadOptions = {
  15. offset: readSize,
  16. length: bufSize
  17. };
  18. // Read the source file content as a stream and write it to the target file.
  19. let readLen = await inputStream.read(buf, readOptions);
  20. readSize += readLen;
  21. while (readLen > 0) {
  22. const writeBuf = readLen < bufSize ? buf.slice(0, readLen) : buf;
  23. await outputStream.write(writeBuf);
  24. readOptions.offset = readSize;
  25. readLen = await inputStream.read(buf, readOptions);
  26. readSize += readLen;
  27. }
  28. console.info(`Succeeded in reading and writing file with stream.`);
  29. } catch (err) {
  30. console.error(`Failed to read and write file with stream. Code: ${err.code}, message: ${err.message}`);
  31. } finally {
  32. try {
  33. if (inputStream) {
  34. inputStream.closeSync();
  35. }
  36. if (outputStream) {
  37. outputStream.closeSync();
  38. }
  39. } catch (closeErr) {
  40. console.error(`Failed to close stream`);
  41. }
  42. }
  43. }
NOTE

Close the stream once it is not required.

Comply with the programming specifications for Stream APIs in asynchronous mode and avoid mixed use of the APIs in synchronous mode and asynchronous mode.

The Stream APIs do not support concurrent read and write operations.

Listing Files

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

Collapse
Word wrap
Dark theme
Copy code
  1. import { fileIo, Filter, ListFileOptions } from '@kit.CoreFileKit';
  2. import { common } from '@kit.AbilityKit';
  3. // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
  4. let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
Collapse
Word wrap
Dark theme
Copy code
  1. function getListFile(context: common.UIAbilityContext): void {
  2. let listFileOption: ListFileOptions = {
  3. recursion: false,
  4. listNum: 0,
  5. filter: {
  6. suffix: ['.png', '.jpg', '.txt'],
  7. displayName: ['test*'],
  8. fileSizeOver: 0,
  9. lastModifiedAfter: new Date(0).getTime()
  10. }
  11. };
  12. let filesDir = context.filesDir;
  13. try {
  14. let files = fileIo.listFileSync(filesDir, listFileOption);
  15. for (let i = 0; i < files.length; i++) {
  16. console.info(`Succeeded in listing file, The name of file: ${files[i]}`);
  17. }
  18. } catch (err) {
  19. console.error(`Failed to list file. Code: ${err.code}, message: ${err.message}`);
  20. }
  21. }

Using File Streams

The following example demonstrates how to use readable and writable streams.

Collapse
Word wrap
Dark theme
Copy code
  1. // pages/xxx.ets
  2. import { fileIo } from '@kit.CoreFileKit';
  3. import { common } from '@kit.AbilityKit';
  4. // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
  5. let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
Collapse
Word wrap
Dark theme
Copy code
  1. function copyFileWithReadable(context: common.UIAbilityContext): void {
  2. try {
  3. let filesDir = context.filesDir;
  4. // Create a readable file stream.
  5. const rs = fileIo.createReadStream(`${filesDir}/test.txt`);
  6. // Create a writable file stream.
  7. const ws = fileIo.createWriteStream(`${filesDir}/destFile.txt`);
  8. // Copy the file in pause mode. During data copying, the source data is paused and then copied to another location. This mode is suitable for scenarios that require high data integrity and consistency.
  9. rs.on('readable', () => {
  10. const data = rs.read();
  11. if (!data) {
  12. return;
  13. }
  14. ws.write(data);
  15. });
  16. rs.on('end', () => {
  17. ws.end();
  18. console.info(`Succeeded in copying file with read stream.`);
  19. });
  20. // Catch exceptions.
  21. rs.on('error', () => {
  22. rs.close();
  23. ws.close();
  24. });
  25. } catch (err) {
  26. console.error(`Failed to copy file with read stream. Code: ${err.code}, message: ${err.message}`);
  27. }
  28. }
Collapse
Word wrap
Dark theme
Copy code
  1. function copyFileWithData(context: common.UIAbilityContext): void {
  2. let filesDir = context.filesDir;
  3. try {
  4. // Create a readable file stream.
  5. let rs = fileIo.createReadStream(`${filesDir}/test.txt`);
  6. // Create a writable file stream.
  7. let ws = fileIo.createWriteStream(`${filesDir}/destFile.txt`);
  8. rs.push('Hello world');
  9. // Copy the file in flowing mode.
  10. rs.on('data', (emitData) => {
  11. const data = emitData?.data;
  12. if (!data) {
  13. return;
  14. }
  15. ws.write(data as Uint8Array);
  16. });
  17. rs.on('end', () => {
  18. ws.end();
  19. console.info(`Succeeded in copying file with data.`);
  20. });
  21. // Catch exceptions.
  22. rs.on('error', () => {
  23. rs.close();
  24. ws.close();
  25. });
  26. } catch (err) {
  27. console.error(`Failed to copy file with data. Code: ${err.code}, message: ${err.message}`);
  28. }
  29. }

Using File Hash Streams

A hash stream is a data transmission and storage technology that can convert data of any length into a hash value of a fixed length to verify data integrity and consistency. The following code shows how to use the file hash processing API ohos.file.hash to process file hash streams.

Collapse
Word wrap
Dark theme
Copy code
  1. // pages/xxx.ets
  2. import { fileIo } from '@kit.CoreFileKit';
  3. import { hash } from '@kit.CoreFileKit';
  4. import { common } from '@kit.AbilityKit';
  5. // Obtain the application file path. The context should be obtained in the component.
  6. let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
Collapse
Word wrap
Dark theme
Copy code
  1. function hashFileWithStream(context: common.UIAbilityContext) {
  2. try {
  3. let filesDir = context.filesDir;
  4. const filePath = `${filesDir}/test.txt`;
  5. // Create a readable file stream.
  6. const rs = fileIo.createReadStream(filePath);
  7. // Create a hash stream.
  8. const hs = hash.createHash('sha256');
  9. rs.on('data', (emitData) => {
  10. const data = emitData?.data;
  11. hs.update(new Uint8Array(data?.split('').map((x: string) => x.charCodeAt(0))).buffer);
  12. });
  13. rs.on('end', async () => {
  14. const hashResult = hs.digest();
  15. const fileHash = await hash.hash(filePath, 'sha256');
  16. console.info(`Succeeded in hashing file with stream, hash result: ${hashResult}, file hash: ${fileHash}`);
  17. });
  18. } catch (err) {
  19. console.error(`Failed to hash file with stream. Code: ${err.code}, message: ${err.message}`);
  20. }
  21. }