app-file-access.md 7.4 KB
Newer Older
A
Annie_wang 已提交
1 2
# Accessing Application Files

A
Annie_wang 已提交
3
This topic describes how to enable an application to view, create, read, write, delete, move, or copy an application and obtain file information.
A
Annie_wang 已提交
4 5 6

## Available APIs

A
Annie_wang 已提交
7
You can use [ohos.file.fs](../reference/apis/js-apis-file-fs.md) to implement access to application files. The following table describes the APIs.
A
Annie_wang 已提交
8 9 10

**Table 1** APIs for basic application file operations

A
Annie_wang 已提交
11
| API| Description| Type| Synchronous Programming| Asynchronous Programming|
A
Annie_wang 已提交
12
| -------- | -------- | -------- | -------- | -------- |
A
Annie_wang 已提交
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| access | Checks whether a file exists.| Method| √ | √ |
| close | Closes a file.| Method| √ | √ |
| copyFile | Copies a file.| Method| √ | √ |
| createStream | Creates a stream based on the specified file path.| Method| √ | √ |
| listFile | Lists all files in a directory.| Method| √ | √ |
| mkdir | Creates a directory.| Method| √ | √ |
| moveFile | Moves a file.| Method| √ | √ |
| open | Opens a file.| Method| √ | √ |
| read | Reads data from a file.| Method| √ | √ |
| rename | Renames a file or folder.| Method| √ | √ |
| rmdir | Deletes a directory.| Method| √ | √ |
| stat | Obtains detailed file information.| Method| √ | √ |
| unlink | Deletes a single file.| Method| √ | √ |
| write | Writes data to a file.| Method| √ | √ |
| Stream.close | Closes a stream.| Method| √ | √ |
| Stream.flush | Flushes all data from this stream.| Method| √ | √ |
| Stream.write | Writes data to a stream.| Method| √ | √ |
| Stream.read | Reads data from a stream.| Method| √ | √ |
| File.fd | Defines a file descriptor.| Attribute| √ | × |
| OpenMode | Defines the mode for opening a file.| Attribute| √ | × |
| Filter | Defines the options for setting the file filter.| Type| × | × |
A
Annie_wang 已提交
34 35 36

## Development Example

A
Annie_wang 已提交
37
First, 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).
A
Annie_wang 已提交
38

A
Annie_wang 已提交
39
Then, perform file operations.
A
Annie_wang 已提交
40 41 42 43 44 45 46 47 48

### Creating, Reading, and Writing a File

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

```ts
// pages/xxx.ets
import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
A
Annie_wang 已提交
49
import buffer from '@ohos.buffer';
A
Annie_wang 已提交
50

A
Annie_wang 已提交
51 52 53
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
A
Annie_wang 已提交
54

A
Annie_wang 已提交
55 56
function createFile() {
    // Create a file and open it.
A
Annie_wang 已提交
57 58 59 60 61
  let file = fs.openSync(filesDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  // Write data to the file.
  let writeLen = fs.writeSync(file.fd, "Try to write str.");
  console.info("The length of str is: " + writeLen);
  // Read data from the file.
A
Annie_wang 已提交
62 63 64 65 66 67 68 69 70 71
  let arrayBuffer = new ArrayBuffer(1024);
  class Option {
    public offset: number = 0;
    public length: number;
  }
  let option = new Option();
  option.length = arrayBuffer.byteLength;
  let readLen = fs.readSync(file.fd, arrayBuffer, option);
  let buf = buffer.from(arrayBuffer, 0, readLen);
  console.info("the content of file: " + buf.toString());
A
Annie_wang 已提交
72 73 74 75 76 77 78
  // Close the file.
  fs.closeSync(file);
}
```

### Copying Data to Another File

A
Annie_wang 已提交
79 80
  The following example demonstrates how to read data from a file and write it to another file.

A
Annie_wang 已提交
81 82 83 84 85
```ts
// pages/xxx.ets
import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';

A
Annie_wang 已提交
86 87 88
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
A
Annie_wang 已提交
89

A
Annie_wang 已提交
90
function readWriteFile() {
A
Annie_wang 已提交
91 92 93 94 95 96 97
  // Open the source and destination files.
  let srcFile = fs.openSync(filesDir + '/test.txt', fs.OpenMode.READ_WRITE);
  let destFile = fs.openSync(filesDir + '/destFile.txt', fs.OpenMode.READ_WRITE | fs.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);
A
Annie_wang 已提交
98 99 100 101 102 103 104
  class Option {
    public offset: number = 0;
    public length: number = bufSize;
  }
  let option = new Option();
  option.offset = readSize;
  let readLen = fs.readSync(srcFile.fd, buf, option);
A
Annie_wang 已提交
105 106 107
  while (readLen > 0) {
    readSize += readLen;
    fs.writeSync(destFile.fd, buf);
A
Annie_wang 已提交
108 109
    option.offset = readSize;
    readLen = fs.readSync(srcFile.fd, buf, option);
A
Annie_wang 已提交
110 111 112 113 114 115 116 117 118
  }
  // Close the files.
  fs.closeSync(srcFile);
  fs.closeSync(destFile);
}
```

> **NOTE**
>
A
Annie_wang 已提交
119
> 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.
A
Annie_wang 已提交
120 121 122 123

### Reading and Writing Files in a Stream

The following example demonstrates how to read and write file data using a stream.
A
Annie_wang 已提交
124

A
Annie_wang 已提交
125 126 127 128 129
```ts
// pages/xxx.ets
import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';

A
Annie_wang 已提交
130 131 132
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
A
Annie_wang 已提交
133

A
Annie_wang 已提交
134
async function readWriteFileWithStream() {
A
Annie_wang 已提交
135 136 137 138 139 140 141
  // Open the file streams.
  let inputStream = fs.createStreamSync(filesDir + '/test.txt', 'r+');
  let outputStream = fs.createStreamSync(filesDir + '/destFile.txt', "w+");
  // Read data from the source file and write the data to the destination file using a stream.
  let bufSize = 4096;
  let readSize = 0;
  let buf = new ArrayBuffer(bufSize);
A
Annie_wang 已提交
142 143 144 145 146 147 148
  class Option {
    public offset: number = 0;
    public length: number = bufSize;
  }
  let option = new Option();
  option.offset = readSize;
  let readLen = await inputStream.read(buf, option);
A
Annie_wang 已提交
149 150 151
  readSize += readLen;
  while (readLen > 0) {
    await outputStream.write(buf);
A
Annie_wang 已提交
152 153
    option.offset = readSize;
    readLen = await inputStream.read(buf, option);
A
Annie_wang 已提交
154 155 156 157 158 159 160 161 162
    readSize += readLen;
  }
  // Close the streams.
  inputStream.closeSync();
  outputStream.closeSync();
}
```

> **NOTE**
A
Annie_wang 已提交
163 164 165 166
>
> - Close the stream that is no longer used in a timely manner. 
> - 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.
A
Annie_wang 已提交
167 168 169

### Listing Files

A
Annie_wang 已提交
170
The following example demonstrates how to list files that meet the specified conditions.
A
Annie_wang 已提交
171 172

```ts
A
Annie_wang 已提交
173
import fs, { Filter } from '@ohos.file.fs';
A
Annie_wang 已提交
174 175 176 177 178 179 180
import common from '@ohos.app.ability.common';

// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;

// List files that meet the specified conditions.
A
Annie_wang 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
function getListFile() {
  class ListFileOption {
    public recursion: boolean = false;
    public listNum: number = 0;
    public filter: Filter
  }
  let option = new ListFileOption();
  option.filter.suffix = ['.png', '.jpg', '.txt'];          // The filen ame extension can be '.png', '.jpg', or '.txt'.
  option.filter.displayName = ['test%'];                    // The file name starts with 'test'.
  option.filter.fileSizeOver = 0;                           // The file size is greater than or equal to 0.
  option.filter.lastModifiedAfter = new Date(0).getTime();  // The latest modification time of the file is later than January 1, 1970.
  let files = fs.listFileSync(filesDir, option);
  for (let i = 0; i < files.length; i++) {
    console.info(`The name of file: ${files[i]}`);
  }
A
Annie_wang 已提交
196 197
}
```