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