• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Accessing Application Files (ArkTS)
2<!--Kit: Core File Kit-->
3<!--Subsystem: FileManagement-->
4<!--Owner: @wangke25; @gsl_1234; @wuchengjun5-->
5<!--Designer: @gsl_1234; @wangke25-->
6<!--Tester: @liuhonggang123; @yue-ye2; @juxiaopang-->
7<!--Adviser: @foryourself-->
8
9This topic describes how to enable an application to view, create, read, write, delete, move, or copy an application file and obtain file information.
10
11## Available APIs
12
13You can use [ohos.file.fs](../reference/apis-core-file-kit/js-apis-file-fs.md) to implement access to application files. The following table describes the commonly used APIs.
14
15Table 1 Functions of ohos.file.fs APIs
16
17| API| Description| Category| Synchronous Programming| Asynchronous Programming|
18| -------- | -------- | -------- | -------- | -------- |
19| access | Checks whether a file exists.| Method| Supported| Supported|
20| close | Closes a file.| Method| Supported| Supported|
21| copyFile | Copies a file.| Method| Supported| Supported|
22| createStream | Creates a stream based on a file path.| Method| Supported| Supported|
23| listFile | Lists all files in a directory.| Method| Supported| Supported|
24| mkdir | Creates a directory.| Method| Supported| Supported|
25| moveFile | Moves a file.| Method| Supported| Supported|
26| open | Opens a file.| Method| Supported| Supported|
27| read | Reads data from a file.| Method| Supported| Supported|
28| rename | Renames a file or folder.| Method| Supported| Supported|
29| rmdir | Removes a directory.| Method| Supported| Supported|
30| stat | Obtains detailed file information.| Method| Supported| Supported|
31| unlink | Deletes a single file.| Method| Supported| Supported|
32| write | Writes data to a file.| Method| Supported| Supported|
33| Stream.close | Closes a stream.| Method| Supported| Supported|
34| Stream.flush | Flushes all data from this stream.| Method| Supported| Supported|
35| Stream.write | Writes data to a stream.| Method| Supported| Supported|
36| Stream.read | Reads data from a stream.| Method| Supported| Supported|
37| File.fd | Defines a file descriptor.| Attribute| N/A| N/A|
38| OpenMode | Defines the mode for opening a file.| Attribute| N/A| N/A|
39| Filter | Defines the options for filtering files.| Type| N/A| N/A|
40
41> **NOTE**
42>
43> 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.
44
45## Development Example
46
47Before performing any file operation, obtain the [application file path](../application-models/application-context-stage.md#obtaining-application-file-paths). 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](../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
48
49The following walks you through on how to perform common file operations.
50
51### Creating, Reading, and Writing a File
52
53The following example demonstrates how to create a file, read data from it, and write data to it.
54
55```ts
56// pages/xxx.ets
57import { fileIo as fs, ReadOptions } from '@kit.CoreFileKit';
58import { common } from '@kit.AbilityKit';
59import { buffer } from '@kit.ArkTS';
60
61// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
62let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
63
64function createFile(context: common.UIAbilityContext): void {
65  let filesDir = context.filesDir;
66  // Create and open a file if the file does not exist. Open it if the file exists.
67  let file = fs.openSync(filesDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
68  // Write data to the file.
69  let writeLen = fs.writeSync(file.fd, "Try to write str.");
70  console.info("The length of str is: " + writeLen);
71  // Create an ArrayBuffer object whose size is 1024 bytes to store the data read from the file.
72  let arrayBuffer = new ArrayBuffer(1024);
73  // Set the offset and length to be read.
74  let readOptions: ReadOptions = {
75    offset: 0,
76    length: arrayBuffer.byteLength
77  };
78  // Read the file content to the ArrayBuffer object and return the number of bytes read.
79  let readLen = fs.readSync(file.fd, arrayBuffer, readOptions);
80  // Convert the ArrayBuffer object into a Buffer object and output it as a string.
81  let buf = buffer.from(arrayBuffer, 0, readLen);
82  console.info("the content of file: " + buf.toString());
83  // Close the file.
84  fs.closeSync(file);
85}
86```
87
88### Copying Data to Another File
89
90The following example demonstrates how to read data from a file and copy it to another file.
91
92```ts
93// pages/xxx.ets
94import { fileIo as fs, ReadOptions, WriteOptions } from '@kit.CoreFileKit';
95import { common } from '@kit.AbilityKit';
96
97// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
98let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
99
100function readWriteFile(context: common.UIAbilityContext): void {
101  let filesDir = context.filesDir;
102  // Open a file.
103  let srcFile = fs.openSync(filesDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
104  let destFile = fs.openSync(filesDir + '/destFile.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
105  // Read data from the source file and copy it to the destination file.
106  let bufSize = 4096;
107  let readSize = 0;
108  let buf = new ArrayBuffer(bufSize);
109  let readOptions: ReadOptions = {
110    offset: readSize,
111    length: bufSize
112  };
113  let readLen = fs.readSync(srcFile.fd, buf, readOptions);
114  while (readLen > 0) {
115    readSize += readLen;
116    let writeOptions: WriteOptions = {
117      length: readLen
118    };
119    fs.writeSync(destFile.fd, buf, writeOptions);
120    readOptions.offset = readSize;
121    readLen = fs.readSync(srcFile.fd, buf, readOptions);
122  }
123  // Close the file.
124  fs.closeSync(srcFile);
125  fs.closeSync(destFile);
126}
127```
128
129> **NOTE**
130>
131> 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.
132
133### Reading and Writing Files in a Stream
134
135The 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.
136
137```ts
138// pages/xxx.ets
139import { fileIo as fs, ReadOptions } from '@kit.CoreFileKit';
140import { common } from '@kit.AbilityKit';
141
142// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
143let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
144
145async function readWriteFileWithStream(context: common.UIAbilityContext): Promise<void> {
146  let filesDir = context.filesDir;
147  // Create and open an input file stream.
148  let inputStream = fs.createStreamSync(filesDir + '/test.txt', 'r+');
149  // Create and open an output file stream.
150  let outputStream = fs.createStreamSync(filesDir + '/destFile.txt', "w+");
151
152  let bufSize = 4096;
153  let readSize = 0;
154  let buf = new ArrayBuffer(bufSize);
155  let readOptions: ReadOptions = {
156    offset: readSize,
157    length: bufSize
158  };
159  // Read data from the source file and write the data to the destination file using a stream.
160  let readLen = await inputStream.read(buf, readOptions);
161  readSize += readLen;
162  while (readLen > 0) {
163    const writeBuf = readLen < bufSize ? buf.slice(0, readLen) : buf;
164    await outputStream.write(writeBuf);
165    readOptions.offset = readSize;
166    readLen = await inputStream.read(buf, readOptions);
167    readSize += readLen;
168  }
169  // Close the streams.
170  inputStream.closeSync();
171  outputStream.closeSync();
172}
173```
174
175> **NOTE**
176>
177> Close the stream once it is not required. <br>Comply with the programming specifications for **Stream** APIs in asynchronous mode and avoid mixed use of the APIs in synchronous mode and asynchronous mode. <br>The **Stream** APIs do not support concurrent read and write operations.
178
179### Listing Files
180
181The following example demonstrates how to list files that meet the specified conditions.
182
183```ts
184import { fileIo as fs, Filter, ListFileOptions } from '@kit.CoreFileKit';
185import { common } from '@kit.AbilityKit';
186
187// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
188let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
189
190// List files that meet the specified conditions.
191function getListFile(context: common.UIAbilityContext): void {
192  let listFileOption: ListFileOptions = {
193    recursion: false,
194    listNum: 0,
195    filter: {
196      suffix: [".png", ".jpg", ".txt"],
197      displayName: ["test*"],
198      fileSizeOver: 0,
199      lastModifiedAfter: new Date(0).getTime()
200    }
201  };
202  let filesDir = context.filesDir;
203  let files = fs.listFileSync(filesDir, listFileOption);
204  for (let i = 0; i < files.length; i++) {
205    console.info(`The name of file: ${files[i]}`);
206  }
207}
208```
209
210### Using File Streams
211
212The following example demonstrates how to use readable and writable streams.
213
214```ts
215// pages/xxx.ets
216import { fileIo as fs } from '@kit.CoreFileKit';
217import { common } from '@kit.AbilityKit';
218
219// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
220let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
221
222function copyFileWithReadable(context: common.UIAbilityContext): void {
223  let filesDir = context.filesDir;
224  // Create a readable stream.
225  const rs = fs.createReadStream(`${filesDir}/read.txt`);
226  // Create a writable stream.
227  const ws = fs.createWriteStream(`${filesDir}/write.txt`);
228  // Copy files in paused mode. Pause file operation and copy the original file data to another location, to ensure data integrity and consistency.
229  rs.on('readable', () => {
230    const data = rs.read();
231    if (!data) {
232      return;
233    }
234    ws.write(data);
235  });
236}
237
238function copyFileWithData(context: common.UIAbilityContext): void {
239  let filesDir = context.filesDir;
240  // Create a readable stream.
241  const rs = fs.createReadStream(`${filesDir}/read.txt`);
242  // Create a writable stream.
243  const ws = fs.createWriteStream(`${filesDir}/write.txt`);
244  // Copy files in stream mode. Read and write file data while accessing the original data, to ensure data timeliness.
245  rs.on('data', (emitData) => {
246    const data = emitData?.data;
247    if (!data) {
248      return;
249    }
250    ws.write(data as Uint8Array);
251  });
252}
253```
254
255### Using File Hash Streams
256
257A 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](../reference/apis-core-file-kit/js-apis-file-hash.md) to process file hash streams.
258
259```ts
260// pages/xxx.ets
261import { fileIo as fs } from '@kit.CoreFileKit';
262import { hash } from '@kit.CoreFileKit';
263import { common } from '@kit.AbilityKit';
264
265// Obtain the application file path. The context should be obtained in the component.
266let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
267
268function hashFileWithStream(context: common.UIAbilityContext) {
269  let filesDir = context.filesDir;
270  const filePath = `${filesDir}/test.txt`;
271  // Create a readable stream.
272  const rs = fs.createReadStream(filePath);
273  // Create a hash stream.
274  const hs = hash.createHash('sha256');
275  rs.on('data', (emitData) => {
276    const data = emitData?.data;
277    hs.update(new Uint8Array(data?.split('').map((x: string) => x.charCodeAt(0))).buffer);
278  });
279  rs.on('close', async () => {
280    const hashResult = hs.digest();
281    const fileHash = await hash.hash(filePath, 'sha256');
282    console.info(`hashResult: ${hashResult}, fileHash: ${fileHash}`);
283  });
284}
285
286```
287