• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Accessing Application Files
2
3This topic describes how to view, create, read, write, delete, move, or copy a file in the application file directory and obtain the file information.
4
5## Available APIs
6
7You can use [ohos.file.fs](../reference/apis/js-apis-file-fs.md) to implement the application file access capabilities. The following table describes the APIs.
8
9**Table 1** APIs for basic application file operations
10
11| API| Description| Type| Synchronous Programming| Asynchronous Programming|
12| -------- | -------- | -------- | -------- | -------- |
13| access | Checks whether a file exists.| Method| √ | √ |
14| close | Closes a file.| Method| √ | √ |
15| copyFile | Copies a file.| Method| √ | √ |
16| createStream | Creates a stream based on the specified file path.| Method| √ | √ |
17| listFile | Lists all files in a directory.| Method| √ | √ |
18| mkdir | Creates a directory.| Method| √ | √ |
19| moveFile | Moves a file.| Method| √ | √ |
20| open | Opens a file.| Method| √ | √ |
21| read | Reads data from a file.| Method| √ | √ |
22| rename | Renames a file or folder.| Method| √ | √ |
23| rmdir | Deletes a directory.| Method| √ | √ |
24| stat | Obtains detailed file information.| Method| √ | √ |
25| unlink | Deletes a single file.| Method| √ | √ |
26| write | Writes data to a file.| Method| √ | √ |
27| Stream.close | Closes a stream.| Method| √ | √ |
28| Stream.flush | Flushes all data from this stream.| Method| √ | √ |
29| Stream.write | Writes data to a stream.| Method| √ | √ |
30| Stream.read | Reads data from a stream.| Method| √ | √ |
31| File.fd | Defines a file descriptor.| Attribute| √ | × |
32| OpenMode | Defines the mode for opening a file.| Attribute| √ | × |
33| Filter | Defines the options for setting the file filter.| Type| × | × |
34
35## Development Example
36
37Obtain the [application file path](../application-models/application-context-stage.md#obtaining-the-application-development-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](../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
38
39The following describes common file operations.
40
41### Creating, Reading, and Writing a File
42
43The following example demonstrates how to create a file, read data from it, and write data to it.
44
45```ts
46// pages/xxx.ets
47import fs from '@ohos.file.fs';
48import common from '@ohos.app.ability.common';
49
50function createFile() {
51  // Obtain the application file path.
52  let context = getContext(this) as common.UIAbilityContext;
53  let filesDir = context.filesDir;
54
55  // Create a file and open it.
56  let file = fs.openSync(filesDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
57  // Write data to the file.
58  let writeLen = fs.writeSync(file.fd, "Try to write str.");
59  console.info("The length of str is: " + writeLen);
60  // Read data from the file.
61  let buf = new ArrayBuffer(1024);
62  let readLen = fs.readSync(file.fd, buf, { offset: 0 });
63  console.info("the content of file: " + String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen))));
64  // Close the file.
65  fs.closeSync(file);
66}
67```
68
69### Copying Data to Another File
70
71  The following example demonstrates how to write the data read from a file to another file.
72
73```ts
74// pages/xxx.ets
75import fs from '@ohos.file.fs';
76import common from '@ohos.app.ability.common';
77
78function readWriteFile() {
79  // Obtain the application file path.
80  let context = getContext(this) as common.UIAbilityContext;
81  let filesDir = context.filesDir;
82
83  // Open the source and destination files.
84  let srcFile = fs.openSync(filesDir + '/test.txt', fs.OpenMode.READ_WRITE);
85  let destFile = fs.openSync(filesDir + '/destFile.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
86  // Read data from the source file and copy it to the destination file.
87  let bufSize = 4096;
88  let readSize = 0;
89  let buf = new ArrayBuffer(bufSize);
90  let readLen = fs.readSync(srcFile.fd, buf, { offset: readSize });
91  while (readLen > 0) {
92    readSize += readLen;
93    fs.writeSync(destFile.fd, buf);
94    readLen = fs.readSync(srcFile.fd, buf, { offset: readSize });
95  }
96  // Close the files.
97  fs.closeSync(srcFile);
98  fs.closeSync(destFile);
99}
100```
101
102> **NOTE**
103>
104> When using **read()** or **write()**, pay attention to the optional parameter **offset**. For a file that has been read or written, the offset pointer is at the end position of the last read or write operation by default.
105
106### Reading and Writing Files in a Stream
107
108The following example demonstrates how to read and write file data using a stream.
109
110```ts
111// pages/xxx.ets
112import fs from '@ohos.file.fs';
113import common from '@ohos.app.ability.common';
114
115async function readWriteFileWithStream() {
116  // Obtain the application file path.
117  let context = getContext(this) as common.UIAbilityContext;
118  let filesDir = context.filesDir;
119
120  // Open the file streams.
121  let inputStream = fs.createStreamSync(filesDir + '/test.txt', 'r+');
122  let outputStream = fs.createStreamSync(filesDir + '/destFile.txt', "w+");
123  // Read data from the source file and write the data to the destination file using a stream.
124  let bufSize = 4096;
125  let readSize = 0;
126  let buf = new ArrayBuffer(bufSize);
127  let readLen = await inputStream.read(buf, { offset: readSize });
128  readSize += readLen;
129  while (readLen > 0) {
130    await outputStream.write(buf);
131    readLen = await inputStream.read(buf, { offset: readSize });
132    readSize += readLen;
133  }
134  // Close the streams.
135  inputStream.closeSync();
136  outputStream.closeSync();
137}
138```
139
140> **NOTE**
141>
142> Close the stream that is no longer used in a timely manner. <br>Comply with the related 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.
143
144### Listing Files
145
146The following example demonstrates how to list files.
147
148```ts
149// List files.
150import fs from '@ohos.file.fs';
151import common from '@ohos.app.ability.common';
152
153// Obtain the application file path.
154let context = getContext(this) as common.UIAbilityContext;
155let filesDir = context.filesDir;
156
157// List files that meet the specified conditions.
158let options = {
159  recursion: false,
160  listNum: 0,
161  filter: {
162    suffix: ['.png', '.jpg', '.txt'],          // The filename extension can be '.png', '.jpg', or '.txt'.
163    displayName: ['test%'],                    // The filename starts with 'test'.
164    fileSizeOver: 0,                           // The file size is greater than or equal to 0.
165    lastModifiedAfter: new Date(0).getTime(), // The latest modification time of the file is later than January 1, 1970.
166  },
167}
168let files = fs.listFileSync(filesDir, options);
169for (let i = 0; i < files.length; i++) {
170  console.info(`The name of file: ${files[i]}`);
171}
172```
173