1# @ohos.file.fs (文件管理) 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 9该模块为基础文件操作API,提供基础文件操作能力,包括文件基本管理、文件目录管理、文件信息统计、文件流式读写等常用功能。 10 11> **说明:** 12> 13> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 14 15## 导入模块 16 17```ts 18import { fileIo as fs } from '@kit.CoreFileKit'; 19``` 20 21## 使用说明 22 23使用该功能模块对文件/目录进行操作前,需要先获取其应用沙箱路径,获取方式及其接口用法请参考: 24 25 ```ts 26 import { UIAbility } from '@kit.AbilityKit'; 27 import { window } from '@kit.ArkUI'; 28 29 export default class EntryAbility extends UIAbility { 30 onWindowStageCreate(windowStage: window.WindowStage) { 31 let context = this.context; 32 let pathDir = context.filesDir; 33 } 34 } 35 ``` 36 37获取沙箱路径的方式及其接口用法也可参考:[应用上下文Context-获取应用文件路径](../../application-models/application-context-stage.md#获取应用文件路径)。<br/>将指向资源的字符串称为URI。对于只支持沙箱路径作为入参的接口,可以使用构造fileUri对象并获取其沙箱路径的属性的方式将URI转换为沙箱路径,然后使用文件接口。URI定义解及其转换方式请参考:[文件URI](../../../application-dev/reference/apis-core-file-kit/js-apis-file-fileuri.md)。 38 39## fs.stat 40 41stat(file: string | number): Promise<Stat> 42 43获取文件或目录详细属性信息,使用promise异步回调。 44 45**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 46 47**系统能力**:SystemCapability.FileManagement.File.FileIO 48 49**参数:** 50 51| 参数名 | 类型 | 必填 | 说明 | 52| ------ | ------ | ---- | -------------------------- | 53| file | string \| number | 是 | 文件或目录应用沙箱路径path或已打开的文件描述符fd。 | 54 55**返回值:** 56 57 | 类型 | 说明 | 58 | ---------------------------- | ---------- | 59 | Promise<[Stat](#stat)> | Promise对象。返回文件或目录的具体信息。 | 60 61**错误码:** 62 63接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 64 65**示例:** 66 67 ```ts 68 import { BusinessError } from '@kit.BasicServicesKit'; 69 let filePath = pathDir + "/test.txt"; 70 fs.stat(filePath).then((stat: fs.Stat) => { 71 console.info("get file info succeed, the size of file is " + stat.size); 72 }).catch((err: BusinessError) => { 73 console.error("get file info failed with error message: " + err.message + ", error code: " + err.code); 74 }); 75 ``` 76 77## fs.stat 78 79stat(file: string | number, callback: AsyncCallback<Stat>): void 80 81获取文件或目录的详细属性信息,使用callback异步回调。 82 83**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 84 85**系统能力**:SystemCapability.FileManagement.File.FileIO 86 87**参数:** 88 89| 参数名 | 类型 | 必填 | 说明 | 90| -------- | ---------------------------------- | ---- | ------------------------------ | 91| file | string \| number | 是 | 文件或目录的应用沙箱路径path或已打开的文件描述符fd。 | 92| callback | AsyncCallback<[Stat](#stat)> | 是 | 异步获取文件或目录的信息之后的回调。 | 93 94**错误码:** 95 96接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 97 98**示例:** 99 100 ```ts 101 import { BusinessError } from '@kit.BasicServicesKit'; 102 fs.stat(pathDir, (err: BusinessError, stat: fs.Stat) => { 103 if (err) { 104 console.error("get file info failed with error message: " + err.message + ", error code: " + err.code); 105 } else { 106 console.info("get file info succeed, the size of file is " + stat.size); 107 } 108 }); 109 ``` 110 111## fs.statSync 112 113statSync(file: string | number): Stat 114 115以同步方法获取文件或目录详细属性信息。 116 117**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 118 119**系统能力**:SystemCapability.FileManagement.File.FileIO 120 121**参数:** 122 123| 参数名 | 类型 | 必填 | 说明 | 124| ------ | ------ | ---- | -------------------------- | 125| file | string \| number | 是 | 文件或目录应用沙箱路径path或已打开的文件描述符fd。 | 126 127**返回值:** 128 129 | 类型 | 说明 | 130 | ------------- | ---------- | 131 | [Stat](#stat) | 表示文件或目录的具体信息。 | 132 133**错误码:** 134 135接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 136 137**示例:** 138 139 ```ts 140 let stat = fs.statSync(pathDir); 141 console.info("get file info succeed, the size of file is " + stat.size); 142 ``` 143 144## fs.access 145 146access(path: string, mode?: AccessModeType): Promise<boolean> 147 148检查文件或目录是否存在,或校验操作权限,使用promise异步回调。<br>校验读、写或读写权限不通过会抛出13900012(Permission denied)错误码。 149 150**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 151 152**系统能力**:SystemCapability.FileManagement.File.FileIO 153 154**参数:** 155 156| 参数名 | 类型 | 必填 | 说明 | 157| ------ | ------ | ---- | ------------------------------------------------------------ | 158| path | string | 是 | 文件或目录应用沙箱路径。 | 159| mode<sup>12+</sup> | [AccessModeType](#accessmodetype12) | 否 | 文件或目录校验的权限。不填该参数则默认校验文件是否存在。| 160 161**返回值:** 162 163 | 类型 | 说明 | 164 | ------------------- | ---------------------------- | 165 | Promise<boolean> | Promise对象。返回布尔值。返回true,表示文件存在;返回false,表示文件不存在。 | 166 167**错误码:** 168 169接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 170 171| 错误码ID | 错误信息 | 172| ---------------------------- | ---------- | 173| 401 | 1. 未指定必须的参数;2. 参数类型与接口定义不匹配。 | 174| 13900020 | 非法参数值。 | 175 176**示例:** 177 178 ```ts 179 import { BusinessError } from '@kit.BasicServicesKit'; 180 let filePath = pathDir + "/test.txt"; 181 fs.access(filePath).then((res: boolean) => { 182 if (res) { 183 console.info("file exists"); 184 } else { 185 console.info("file not exists"); 186 } 187 }).catch((err: BusinessError) => { 188 console.error("access failed with error message: " + err.message + ", error code: " + err.code); 189 }); 190 ``` 191 192## fs.access 193 194access(path: string, mode: AccessModeType, flag: AccessFlagType): Promise<boolean> 195 196检查文件或目录是否在本地,或校验操作权限,使用promise异步回调。<br>校验读、写或读写权限不通过会抛出13900012(Permission denied)错误码。 197 198**系统能力**:SystemCapability.FileManagement.File.FileIO 199 200**参数:** 201 202| 参数名 | 类型 | 必填 | 说明 | 203| ------ | ------ | ---- | ------------------------------------------------------------ | 204| path | string | 是 | 文件或目录应用沙箱路径。 | 205| mode<sup>12+</sup> | [AccessModeType](#accessmodetype12) | 是 | 文件或目录校验的权限。| 206| flag<sup>12+</sup> | [AccessFlagType](#accessflagtype12) | 是| 文件或目录校验的位置。 | 207 208**返回值:** 209 210 | 类型 | 说明 | 211 | ------------------- | ---------------------------- | 212 | Promise<boolean> | Promise对象。返回布尔值。返回true,表示文件或目录在本地且校验权限存在;返回false,表示文件或目录不存在或者文件或目录在云端或其他分布式设备上。 | 213 214**错误码:** 215 216接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 217 218| 错误码ID | 错误信息 | 219| ---------------------------- | ---------- | 220| 401 | 1. 未指定必须的参数;2. 参数类型与接口定义不匹配。 | 221| 13900020 | 非法参数值。 | 222 223**示例:** 224 225 ```ts 226 import { BusinessError } from '@kit.BasicServicesKit'; 227 let filePath = pathDir + "/test.txt"; 228 fs.access(filePath, fs.AccessModeType.EXIST, fs.AccessFlagType.LOCAL).then((res: boolean) => { 229 if (res) { 230 console.info("file exists"); 231 } else { 232 console.info("file not exists"); 233 } 234 }).catch((err: BusinessError) => { 235 console.error("access failed with error message: " + err.message + ", error code: " + err.code); 236 }); 237 ``` 238 239## fs.access 240 241access(path: string, callback: AsyncCallback<boolean>): void 242 243检查文件或目录是否存在,使用callback异步回调。 244 245**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 246 247**系统能力**:SystemCapability.FileManagement.File.FileIO 248 249**参数:** 250 251| 参数名 | 类型 | 必填 | 说明 | 252| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 253| path | string | 是 | 文件或目录应用沙箱路径。 | 254| callback | AsyncCallback<boolean> | 是 | 异步检查文件或目录是否存在的回调。如果存在,回调返回true;否则返回false。 | 255 256**错误码:** 257 258接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 259 260| 错误码ID | 错误信息 | 261| ---------------------------- | ---------- | 262| 401 | 1. 未指定必须的参数;2. 参数类型与接口定义不匹配。 | 263| 13900020 | 非法参数值。| 264 265**示例:** 266 267 ```ts 268 import { BusinessError } from '@kit.BasicServicesKit'; 269 let filePath = pathDir + "/test.txt"; 270 fs.access(filePath, (err: BusinessError, res: boolean) => { 271 if (err) { 272 console.error("access failed with error message: " + err.message + ", error code: " + err.code); 273 } else { 274 if (res) { 275 console.info("file exists"); 276 } else { 277 console.info("file not exists"); 278 } 279 } 280 }); 281 ``` 282 283## fs.accessSync 284 285accessSync(path: string, mode?: AccessModeType): boolean 286 287以同步方法检查文件或目录是否存在,或校验操作权限。<br>校验读、写或读写权限不通过会抛出13900012(Permission denied)错误码。 288 289**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 290 291**系统能力**:SystemCapability.FileManagement.File.FileIO 292 293**参数:** 294 295| 参数名 | 类型 | 必填 | 说明 | 296| ------ | ------ | ---- | ------------------------------------------------------------ | 297| path | string | 是 | 文件或目录应用沙箱路径。 | 298| mode<sup>12+</sup> | [AccessModeType](#accessmodetype12) | 否 | 文件或目录校验的权限。不填该参数则默认校验文件或目录是否存在。 | 299 300**返回值:** 301 302 | 类型 | 说明 | 303 | ------------------- | ---------------------------- | 304 | boolean | 返回true,表示文件存在;返回false,表示文件不存在。 | 305 306**错误码:** 307 308接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 309 310| 错误码ID | 错误信息 | 311| ---------------------------- | ---------- | 312| 401 | 1. 未指定必须的参数;2. 参数类型与接口定义不匹配。 | 313| 13900020 | 非法参数值。 | 314 315**示例:** 316 317 ```ts 318 import { BusinessError } from '@kit.BasicServicesKit'; 319 let filePath = pathDir + "/test.txt"; 320 try { 321 let res = fs.accessSync(filePath); 322 if (res) { 323 console.info("file exists"); 324 } else { 325 console.info("file not exists"); 326 } 327 } catch(error) { 328 let err: BusinessError = error as BusinessError; 329 console.error("accessSync failed with error message: " + err.message + ", error code: " + err.code); 330 } 331 ``` 332 333## fs.accessSync 334 335accessSync(path: string, mode: AccessModeType, flag: AccessFlagType): boolean 336 337以同步方法检查文件或目录是否在本地,或校验操作权限。<br>校验读、写或读写权限不通过会抛出13900012(Permission denied)错误码。 338 339**系统能力**:SystemCapability.FileManagement.File.FileIO 340 341**参数:** 342 343| 参数名 | 类型 | 必填 | 说明 | 344| ------ | ------ | ---- | ------------------------------------------------------------ | 345| path | string | 是 | 文件应用沙箱路径。 | 346| mode<sup>12+</sup> | [AccessModeType](#accessmodetype12) | 是 | 文件或目录校验的权限。| 347| flag<sup>12+</sup> | [AccessFlagType](#accessflagtype12) | 是 | 文件或目录校验的位置。 | 348 349**返回值:** 350 351 | 类型 | 说明 | 352 | ------------------- | ---------------------------- | 353 | boolean | 返回true,表示文件在本地且校验权限存在;返回false,表示文件不存在或者文件在云端或其他分布式设备上。 | 354 355**错误码:** 356 357接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 358 359| 错误码ID | 错误信息 | 360| ---------------------------- | ---------- | 361| 401 | 1. 未指定必须的参数;2. 参数类型与接口定义不匹配。 | 362| 13900020 | 非法参数值。 | 363 364**示例:** 365 366 ```ts 367 import { BusinessError } from '@kit.BasicServicesKit'; 368 let filePath = pathDir + "/test.txt"; 369 try { 370 let res = fs.accessSync(filePath, fs.AccessModeType.EXIST, fs.AccessFlagType.LOCAL); 371 if (res) { 372 console.info("file exists"); 373 } else { 374 console.info("file not exists"); 375 } 376 } catch(error) { 377 let err: BusinessError = error as BusinessError; 378 console.error("accessSync failed with error message: " + err.message + ", error code: " + err.code); 379 } 380 ``` 381 382## fs.close 383 384close(file: number | File): Promise<void> 385 386关闭文件或目录,使用promise异步回调。 387 388**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 389 390**系统能力**:SystemCapability.FileManagement.File.FileIO 391 392**参数:** 393 394 | 参数名 | 类型 | 必填 | 说明 | 395 | ---- | ------ | ---- | ------------ | 396 | file | number \| [File](#file) | 是 | 已打开的File对象或已打开的文件描述符fd。关闭后file对象或文件描述符fd不再具备实际意义,不可再用于进行读写等操作。 | 397 398**返回值:** 399 400 | 类型 | 说明 | 401 | ------------------- | ---------------------------- | 402 | Promise<void> | Promise对象。无返回值。 | 403 404**错误码:** 405 406接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 407 408**示例:** 409 410 ```ts 411 import { BusinessError } from '@kit.BasicServicesKit'; 412 let filePath = pathDir + "/test.txt"; 413 let file = fs.openSync(filePath); 414 fs.close(file).then(() => { 415 console.info("close file succeed"); 416 }).catch((err: BusinessError) => { 417 console.error("close file failed with error message: " + err.message + ", error code: " + err.code); 418 }); 419 ``` 420 421## fs.close 422 423close(file: number | File, callback: AsyncCallback<void>): void 424 425关闭文件或目录,使用callback异步回调。 426 427**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 428 429**系统能力**:SystemCapability.FileManagement.File.FileIO 430 431**参数:** 432 433 | 参数名 | 类型 | 必填 | 说明 | 434 | -------- | ------------------------- | ---- | ------------ | 435 | file | number \| [File](#file) | 是 | 已打开的File对象或已打开的文件描述符fd。关闭后file对象或文件描述符fd不再具备实际意义,不可再用于进行读写等操作。 | 436 | callback | AsyncCallback<void> | 是 | 异步关闭文件或目录之后的回调。 | 437 438**错误码:** 439 440接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 441 442**示例:** 443 444 ```ts 445 import { BusinessError } from '@kit.BasicServicesKit'; 446 let filePath = pathDir + "/test.txt"; 447 let file = fs.openSync(filePath); 448 fs.close(file, (err: BusinessError) => { 449 if (err) { 450 console.error("close file failed with error message: " + err.message + ", error code: " + err.code); 451 } else { 452 console.info("close file succeed"); 453 } 454 }); 455 ``` 456 457## fs.closeSync 458 459closeSync(file: number | File): void 460 461以同步方法关闭文件或目录。 462 463**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 464 465**系统能力**:SystemCapability.FileManagement.File.FileIO 466 467**参数:** 468 469 | 参数名 | 类型 | 必填 | 说明 | 470 | ---- | ------ | ---- | ------------ | 471 | file | number \| [File](#file) | 是 | 已打开的File对象或已打开的文件描述符fd。关闭后file对象或文件描述符fd不再具备实际意义,不可再用于进行读写等操作。 | 472 473**错误码:** 474 475接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 476 477**示例:** 478 479 ```ts 480 let filePath = pathDir + "/test.txt"; 481 let file = fs.openSync(filePath); 482 fs.closeSync(file); 483 ``` 484 485## fs.copy<sup>11+</sup> 486 487copy(srcUri: string, destUri: string, options?: CopyOptions): Promise\<void> 488 489拷贝文件或目录,使用promise异步回调。 490 491支持跨设备拷贝。强制覆盖拷贝。入参支持文件或目录URI。<br/> 492跨端拷贝时,最多同时存在10个拷贝任务;单次拷贝的文件数量不得超过500个。 493 494**系统能力**:SystemCapability.FileManagement.File.FileIO 495 496**参数:** 497 498 | 参数名 | 类型 | 必填 | 说明 | 499 | ---- | -------------------------- | ---- | ---------------------------------------- | 500 | srcUri | string | 是 | 待复制文件或目录的URI。 | 501 | destUri | string | 是 | 目标文件或目录的URI。 | 502 | options | [CopyOptions](#copyoptions11)| 否| options中提供拷贝进度回调。不填该参数则无拷贝进度回调。| 503 504**返回值:** 505 506 | 类型 | 说明 | 507 | ------------------- | ---------------------------- | 508 | Promise\<void> | Promise对象。无返回值。 | 509 510**错误码:** 511 512接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 513 514**示例:** 515 516```ts 517import { fileIo as fs } from '@kit.CoreFileKit'; 518import { BusinessError } from '@kit.BasicServicesKit'; 519import { fileUri } from '@kit.CoreFileKit'; 520 521let srcDirPathLocal: string = pathDir + "/src"; 522let dstDirPathLocal: string = pathDir + "/dest"; 523 524let srcDirUriLocal: string = fileUri.getUriFromPath(srcDirPathLocal); 525let dstDirUriLocal: string = fileUri.getUriFromPath(dstDirPathLocal); 526 527let progressListener: fs.ProgressListener = (progress: fs.Progress) => { 528 console.info(`progressSize: ${progress.processedSize}, totalSize: ${progress.totalSize}`); 529}; 530let copyOption: fs.CopyOptions = { 531 "progressListener" : progressListener 532} 533try { 534 fs.copy(srcDirUriLocal, dstDirUriLocal, copyOption).then(()=>{ 535 console.info("Succeeded in copying."); 536 }).catch((err: BusinessError)=>{ 537 console.error(`Failed to copy. Code: ${err.code}, message: ${err.message}`); 538 }) 539} catch(err) { 540 console.error(`Failed to copy.Code: ${err.code}, message: ${err.message}`); 541} 542``` 543 544## fs.copy<sup>11+</sup> 545 546copy(srcUri: string, destUri: string, callback: AsyncCallback\<void>): void 547 548拷贝文件或者目录,使用callback异步回调。 549 550支持跨设备拷贝。强制覆盖拷贝。入参支持文件或目录URI。<br/> 551跨端拷贝时,最多同时存在10个拷贝任务;单次拷贝的文件数量不得超过500个。 552 553**系统能力**:SystemCapability.FileManagement.File.FileIO 554 555**参数:** 556 557 | 参数名 | 类型 | 必填 | 说明 | 558 | ---- | ------------------ | ---- | ----------------------------| 559 | srcUri | string | 是 | 待复制文件或目录的URI。 | 560 | destUri | string | 是 | 目标文件或目录的URI。 | 561 | callback | AsyncCallback\<void>| 是| 异步拷贝之后的回调。| 562 563**错误码:** 564 565接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 566 567**示例:** 568 569```ts 570import { BusinessError } from '@kit.BasicServicesKit'; 571import { fileUri } from '@kit.CoreFileKit'; 572 573let srcDirPathLocal: string = pathDir + "/src"; 574let dstDirPathLocal: string = pathDir + "/dest"; 575 576let srcDirUriLocal: string = fileUri.getUriFromPath(srcDirPathLocal); 577let dstDirUriLocal: string = fileUri.getUriFromPath(dstDirPathLocal); 578 579try { 580 fs.copy(srcDirUriLocal, dstDirUriLocal, (err: BusinessError) => { 581 if (err) { 582 console.error(`Failed to copy. Code: ${err.code}, message: ${err.message}`); 583 return; 584 } 585 console.info("Succeeded in copying."); 586 }) 587} catch(err) { 588 console.error(`Failed to copy. Code: ${err.code}, message: ${err.message}`); 589} 590``` 591 592## fs.copy<sup>11+</sup> 593 594copy(srcUri: string, destUri: string, options: CopyOptions, callback: AsyncCallback\<void>): void 595 596拷贝文件或者目录,使用callback异步回调。 597 598支持跨设备拷贝。强制覆盖拷贝。入参支持文件或目录URI。<br/> 599跨端拷贝时,最多同时存在10个拷贝任务;单次拷贝的文件数量不得超过500个。 600 601**系统能力**:SystemCapability.FileManagement.File.FileIO 602 603**参数:** 604 605 | 参数名 | 类型 | 必填 | 说明 | 606 | ---- | -------------------------- | ---- | ---------------------------------------- | 607 | srcUri | string | 是 | 待复制文件或目录的URI。 | 608 | destUri | string | 是 | 目标文件或目录的URI。 | 609 | options | [CopyOptions](#copyoptions11) |是| 拷贝进度回调。 | 610 | callback | AsyncCallback\<void>| 是| 异步拷贝之后的回调。| 611 612**错误码:** 613 614接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 615 616**示例:** 617 618```ts 619import { fileIo as fs } from '@kit.CoreFileKit'; 620import { BusinessError } from '@kit.BasicServicesKit'; 621import { fileUri } from '@kit.CoreFileKit'; 622 623let srcDirPathLocal: string = pathDir + "/src"; 624let dstDirPathLocal: string = pathDir + "/dest"; 625 626let srcDirUriLocal: string = fileUri.getUriFromPath(srcDirPathLocal); 627let dstDirUriLocal: string = fileUri.getUriFromPath(dstDirPathLocal); 628 629try { 630 let progressListener: fs.ProgressListener = (progress: fs.Progress) => { 631 console.info(`progressSize: ${progress.processedSize}, totalSize: ${progress.totalSize}`); 632 }; 633 let copyOption: fs.CopyOptions = { 634 "progressListener" : progressListener 635 } 636 fs.copy(srcDirUriLocal, dstDirUriLocal, copyOption, (err: BusinessError) => { 637 if (err) { 638 console.error(`Failed to copy. Code: ${err.code}, message: ${err.message}`); 639 return; 640 } 641 console.info("Succeeded in copying."); 642 }) 643} catch(err) { 644 console.error(`Failed to copy. Code: ${err.code}, message: ${err.message}`); 645} 646``` 647 648## fs.copyFile 649 650copyFile(src: string | number, dest: string | number, mode?: number): Promise<void> 651 652复制文件,使用promise异步回调。 653 654**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 655 656**系统能力**:SystemCapability.FileManagement.File.FileIO 657 658**参数:** 659 660 | 参数名 | 类型 | 必填 | 说明 | 661 | ---- | -------------------------- | ---- | ---------------------------------------- | 662 | src | string \| number | 是 | 待复制文件的路径或待复制文件的文件描述符。 | 663 | dest | string \| number | 是 | 目标文件路径或目标文件的文件描述符。 | 664 | mode | number | 否 | mode提供覆盖文件的选项,当前仅支持0,且默认为0。<br/>0:完全覆盖目标文件,未覆盖部分将被裁切掉。 | 665 666**返回值:** 667 668 | 类型 | 说明 | 669 | ------------------- | ---------------------------- | 670 | Promise<void> | Promise对象。无返回值。 | 671 672**错误码:** 673 674接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 675 676**示例:** 677 678 ```ts 679 import { BusinessError } from '@kit.BasicServicesKit'; 680 let srcPath = pathDir + "/srcDir/test.txt"; 681 let dstPath = pathDir + "/dstDir/test.txt"; 682 fs.copyFile(srcPath, dstPath, 0).then(() => { 683 console.info("copy file succeed"); 684 }).catch((err: BusinessError) => { 685 console.error("copy file failed with error message: " + err.message + ", error code: " + err.code); 686 }); 687 ``` 688 689## fs.copyFile 690 691copyFile(src: string | number, dest: string | number, mode: number, callback: AsyncCallback<void>): void 692 693复制文件,可设置覆盖文件的方式,使用callback异步回调。 694 695**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 696 697**系统能力**:SystemCapability.FileManagement.File.FileIO 698 699**参数:** 700 701 | 参数名 | 类型 | 必填 | 说明 | 702 | -------- | -------------------------- | ---- | ---------------------------------------- | 703 | src | string \| number | 是 | 待复制文件的路径或待复制文件的文件描述符。 | 704 | dest | string \| number | 是 | 目标文件路径或目标文件的文件描述符。 | 705 | mode | number | 是 | mode提供覆盖文件的选项,当前仅支持0,且默认为0。<br/>0:完全覆盖目标文件,未覆盖部分将被裁切掉。 | 706 | callback | AsyncCallback<void> | 是 | 异步复制文件之后的回调。 | 707 708**错误码:** 709 710接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 711 712**示例:** 713 714 ```ts 715 import { BusinessError } from '@kit.BasicServicesKit'; 716 let srcPath = pathDir + "/srcDir/test.txt"; 717 let dstPath = pathDir + "/dstDir/test.txt"; 718 fs.copyFile(srcPath, dstPath, 0, (err: BusinessError) => { 719 if (err) { 720 console.error("copy file failed with error message: " + err.message + ", error code: " + err.code); 721 } else { 722 console.info("copy file succeed"); 723 } 724 }); 725 ``` 726 727## fs.copyFile 728 729copyFile(src: string | number, dest: string | number, callback: AsyncCallback<void>): void 730 731复制文件,覆盖方式为完全覆盖目标文件,未覆盖部分将被裁切。使用callback异步回调。 732 733**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 734 735**系统能力**:SystemCapability.FileManagement.File.FileIO 736 737**参数:** 738 739 | 参数名 | 类型 | 必填 | 说明 | 740 | -------- | -------------------------- | ---- | ---------------------------------------- | 741 | src | string \| number | 是 | 待复制文件的路径或待复制文件的文件描述符。 | 742 | dest | string \| number | 是 | 目标文件路径或目标文件的文件描述符。 | 743 | callback | AsyncCallback<void> | 是 | 异步复制文件之后的回调。 | 744 745**错误码:** 746 747接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 748 749**示例:** 750 751 ```ts 752 import { BusinessError } from '@kit.BasicServicesKit'; 753 let srcPath = pathDir + "/srcDir/test.txt"; 754 let dstPath = pathDir + "/dstDir/test.txt"; 755 fs.copyFile(srcPath, dstPath, (err: BusinessError) => { 756 if (err) { 757 console.error("copy file failed with error message: " + err.message + ", error code: " + err.code); 758 } else { 759 console.info("copy file succeed"); 760 } 761 }); 762 ``` 763 764 765## fs.copyFileSync 766 767copyFileSync(src: string | number, dest: string | number, mode?: number): void 768 769以同步方法复制文件。 770 771**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 772 773**系统能力**:SystemCapability.FileManagement.File.FileIO 774 775**参数:** 776 777 | 参数名 | 类型 | 必填 | 说明 | 778 | ---- | -------------------------- | ---- | ---------------------------------------- | 779 | src | string \| number | 是 | 待复制文件的路径或待复制文件的文件描述符。 | 780 | dest | string \| number | 是 | 目标文件路径或目标文件的文件描述符。 | 781 | mode | number | 否 | mode提供覆盖文件的选项,当前仅支持0,且默认为0。<br/>0:完全覆盖目标文件,未覆盖部分将被裁切掉。 | 782 783**错误码:** 784 785接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 786 787**示例:** 788 789 ```ts 790 let srcPath = pathDir + "/srcDir/test.txt"; 791 let dstPath = pathDir + "/dstDir/test.txt"; 792 fs.copyFileSync(srcPath, dstPath); 793 ``` 794 795## fs.copyDir<sup>10+</sup> 796 797copyDir(src: string, dest: string, mode?: number): Promise\<void> 798 799复制源目录至目标路径下,使用promise异步回调。 800 801**系统能力**:SystemCapability.FileManagement.File.FileIO 802 803**参数:** 804 805 | 参数名 | 类型 | 必填 | 说明 | 806 | ------ | ------ | ---- | --------------------------- | 807 | src | string | 是 | 源目录的应用沙箱路径。 | 808 | dest | string | 是 | 目标目录的应用沙箱路径。 | 809 | mode | number | 否 | 复制模式,默认值为0。<br/>- mode为0,文件级别抛异常。目标目录下存在与源目录名冲突的目录,若冲突目录下存在同名文件,则抛出异常。源目录下未冲突的文件全部移动至目标目录下,目标目录下未冲突文件将继续保留,且冲突文件信息将在抛出异常的data属性中以Array\<[ConflictFiles](#conflictfiles10)>形式提供。<br/>- mode为1,文件级别强制覆盖。目标目录下存在与源目录名冲突的目录,若冲突目录下存在同名文件,则强制覆盖冲突目录下所有同名文件,未冲突文件将继续保留。| 810 811**返回值:** 812 813 | 类型 | 说明 | 814 | ------------------- | ---------------------------- | 815 | Promise<void> | Promise对象。无返回值。 | 816 817**错误码:** 818 819接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 820 821**示例:** 822 823 ```ts 824 import { BusinessError } from '@kit.BasicServicesKit'; 825 // copy directory from srcPath to destPath 826 let srcPath = pathDir + "/srcDir/"; 827 let destPath = pathDir + "/destDir/"; 828 fs.copyDir(srcPath, destPath, 0).then(() => { 829 console.info("copy directory succeed"); 830 }).catch((err: BusinessError) => { 831 console.error("copy directory failed with error message: " + err.message + ", error code: " + err.code); 832 }); 833 ``` 834 835## fs.copyDir<sup>10+</sup> 836 837copyDir(src: string, dest: string, mode: number, callback: AsyncCallback\<void, Array\<ConflictFiles>>): void 838 839复制源目录至目标路径下,可设置复制模式。使用callback异步回调。 840 841**系统能力**:SystemCapability.FileManagement.File.FileIO 842 843**参数:** 844 845 | 参数名 | 类型 | 必填 | 说明 | 846 | ------ | ------ | ---- | --------------------------- | 847 | src | string | 是 | 源目录的应用沙箱路径。 | 848 | dest | string | 是 | 目标目录的应用沙箱路径。 | 849 | mode | number | 是 | 复制模式,默认值为0。<br/>- mode为0,文件级别抛异常。目标目录下存在与源目录名冲突的目录,若冲突目录下存在同名文件,则抛出异常。源目录下未冲突的文件全部移动至目标目录下,目标目录下未冲突文件将继续保留,且冲突文件信息将在抛出异常的data属性中以Array\<[ConflictFiles](#conflictfiles10)>形式提供。<br/>- mode为1,文件级别强制覆盖。目标目录下存在与源目录名冲突的目录,若冲突目录下存在同名文件,则强制覆盖冲突目录下所有同名文件,未冲突文件将继续保留。| 850 | callback | AsyncCallback<void, Array<[ConflictFiles](#conflictfiles10)>> | 是 | 异步复制目录之后的回调。 | 851 852**错误码:** 853 854接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 855 856**示例:** 857 858 ```ts 859 import { BusinessError } from '@kit.BasicServicesKit'; 860 import { fileIo as fs, ConflictFiles } from '@kit.CoreFileKit'; 861 // copy directory from srcPath to destPath 862 let srcPath = pathDir + "/srcDir/"; 863 let destPath = pathDir + "/destDir/"; 864 fs.copyDir(srcPath, destPath, 0, (err: BusinessError<Array<ConflictFiles>>) => { 865 if (err && err.code == 13900015 && err.data?.length !== undefined) { 866 for (let i = 0; i < err.data.length; i++) { 867 console.error("copy directory failed with conflicting files: " + err.data[i].srcFile + " " + err.data[i].destFile); 868 } 869 } else if (err) { 870 console.error("copy directory failed with error message: " + err.message + ", error code: " + err.code); 871 } else { 872 console.info("copy directory succeed"); 873 } 874 }); 875 ``` 876 877## fs.copyDir<sup>10+</sup> 878 879copyDir(src: string, dest: string, callback: AsyncCallback\<void, Array\<ConflictFiles>>): void 880 881复制源目录至目标路径下,使用callback异步回调。 882 883如果目标目录下有与源目录名冲突的目录,且冲突目录下有同名文件,则抛出异常。源目录下未冲突的文件全部移动至目标目录下,目标目录下未冲突文件将继续保留,且冲突文件信息将在抛出异常的data属性中以Array\<[ConflictFiles](#conflictfiles10)>形式提供。 884 885**系统能力**:SystemCapability.FileManagement.File.FileIO 886 887**参数:** 888 889 | 参数名 | 类型 | 必填 | 说明 | 890 | ------ | ------ | ---- | --------------------------- | 891 | src | string | 是 | 源目录的应用沙箱路径。 | 892 | dest | string | 是 | 目标目录的应用沙箱路径。 | 893 | callback | AsyncCallback<void, Array<[ConflictFiles](#conflictfiles10)>> | 是 | 异步复制目录之后的回调。 | 894 895**错误码:** 896 897接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 898 899**示例:** 900 901 ```ts 902 import { BusinessError } from '@kit.BasicServicesKit'; 903 import { fileIo as fs, ConflictFiles } from '@kit.CoreFileKit'; 904 // copy directory from srcPath to destPath 905 let srcPath = pathDir + "/srcDir/"; 906 let destPath = pathDir + "/destDir/"; 907 fs.copyDir(srcPath, destPath, (err: BusinessError<Array<ConflictFiles>>) => { 908 if (err && err.code == 13900015 && err.data?.length !== undefined) { 909 for (let i = 0; i < err.data.length; i++) { 910 console.error("copy directory failed with conflicting files: " + err.data[i].srcFile + " " + err.data[i].destFile); 911 } 912 } else if (err) { 913 console.error("copy directory failed with error message: " + err.message + ", error code: " + err.code); 914 } else { 915 console.info("copy directory succeed"); 916 } 917 }); 918 ``` 919 920## fs.copyDirSync<sup>10+</sup> 921 922copyDirSync(src: string, dest: string, mode?: number): void 923 924以同步方法复制源目录至目标路径下。 925 926**系统能力**:SystemCapability.FileManagement.File.FileIO 927 928**参数:** 929 930 | 参数名 | 类型 | 必填 | 说明 | 931 | ------ | ------ | ---- | --------------------------- | 932 | src | string | 是 | 源目录的应用沙箱路径。 | 933 | dest | string | 是 | 目标目录的应用沙箱路径。 | 934 | mode | number | 否 | 复制模式,默认值为0。<br/>- mode为0,文件级别抛异常。目标目录下存在与源目录名冲突的目录,若冲突目录下存在同名文件,则抛出异常。源目录下未冲突的文件全部移动至目标目录下,目标目录下未冲突文件将继续保留,且冲突文件信息将在抛出异常的data属性中以Array\<[ConflictFiles](#conflictfiles10)>形式提供。<br/>- mode为1,文件级别强制覆盖。目标目录下存在与源目录名冲突的目录,若冲突目录下存在同名文件,则强制覆盖冲突目录下所有同名文件,未冲突文件将继续保留。| 935 936**错误码:** 937 938接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 939 940**示例:** 941 942 ```ts 943 import { BusinessError } from '@kit.BasicServicesKit'; 944 // copy directory from srcPath to destPath 945 let srcPath = pathDir + "/srcDir/"; 946 let destPath = pathDir + "/destDir/"; 947 try { 948 fs.copyDirSync(srcPath, destPath, 0); 949 console.info("copy directory succeed"); 950 } catch (error) { 951 let err: BusinessError = error as BusinessError; 952 console.error("copy directory failed with error message: " + err.message + ", error code: " + err.code); 953 } 954 ``` 955 956## fs.dup<sup>10+</sup> 957 958dup(fd: number): File 959 960复制文件描述符,并返回对应的File对象。 961 962**系统能力**:SystemCapability.FileManagement.File.FileIO 963 964**参数:** 965 966 | 参数名 | 类型 | 必填 | 说明 | 967 | ------ | ------ | ---- | --------------------------- | 968 | fd | number | 是 | 文件描述符。 | 969 970**返回值:** 971 972 | 类型 | 说明 | 973 | ------------------- | ---------------------------- | 974 | [File](#file) | 打开的File对象。 | 975 976**错误码:** 977 978接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 979 980**示例:** 981 982 ```ts 983 let filePath = pathDir + "/test.txt"; 984 let file1 = fs.openSync(filePath, fs.OpenMode.READ_WRITE); 985 let fd: number = file1.fd; 986 let file2 = fs.dup(fd); 987 console.info("The name of the file2 is " + file2.name); 988 fs.closeSync(file1); 989 fs.closeSync(file2); 990 ``` 991 992## fs.connectDfs<sup>12+</sup> 993 994connectDfs(networkId: string, listeners: DfsListeners): Promise<void> 995 996业务调用connectDfs接口,触发建链。如果对端设备出现异常,业务执行回调DfsListeners内[onStatus](#onstatus12)通知应用。 997 998**需要权限**:ohos.permission.DISTRIBUTED_DATASYNC 999 1000**系统能力**:SystemCapability.FileManagement.File.FileIO 1001 1002**参数:** 1003 1004 | 参数名 | 类型 | 必填 | 说明 | 1005 | ---- | ------ | ---- | ---------------------------------------- | 1006 | networkId | string | 是 | 设备的网络Id。通过[distributedDeviceManager](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md)接口调用[deviceBasicInfo](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md#devicebasicinfo)获得。 | 1007 | listeners | [DfsListeners](#fsdfslisteners12) | 是 | 分布式文件系统状态监听器。 | 1008 1009**返回值:** 1010 1011 | 类型 | 说明 | 1012 | ------ | ---------------------------------------- | 1013 | Promise<void>| Promise对象。无返回值。 | 1014 1015**错误码:** 1016 1017接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1018 1019**示例:** 1020 1021 ```ts 1022 import { BusinessError } from '@kit.BasicServicesKit'; 1023 import { fileIo as fs } from '@kit.CoreFileKit'; 1024 import { distributedDeviceManager } from '@kit.DistributedServiceKit'; 1025 let dmInstance = distributedDeviceManager.createDeviceManager("com.example.filesync"); 1026 let deviceInfoList: Array<distributedDeviceManager.DeviceBasicInfo> = dmInstance.getAvailableDeviceListSync(); 1027 if (deviceInfoList && deviceInfoList.length > 0) { 1028 console.info(`Success to get available device list`); 1029 let networkId = deviceInfoList[0].networkId; 1030 let listeners: fs.DfsListeners = { 1031 onStatus(networkId, status) { 1032 console.info('onStatus'); 1033 } 1034 }; 1035 fs.connectDfs(networkId, listeners).then(() => { 1036 console.info("Success to connectDfs"); 1037 }).catch((err: BusinessError) => { 1038 console.error(`Failed to connectDfs. Code: ${err.code}, message: ${err.message}`); 1039 }); 1040 } 1041 ``` 1042 1043## fs.disconnectDfs<sup>12+</sup> 1044 1045disconnectDfs(networkId: string): Promise<void> 1046 1047业务调用disconnectDfs接口,传入networkId参数,触发断链。 1048 1049**需要权限**:ohos.permission.DISTRIBUTED_DATASYNC 1050 1051**系统能力**:SystemCapability.FileManagement.File.FileIO 1052 1053**参数:** 1054 1055 | 参数名 | 类型 | 必填 | 说明 | 1056 | ---- | ------ | ---- | ---------------------------------------- | 1057 | networkId | string | 是 | 设备的网络Id。通过[distributedDeviceManager](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md)接口调用[deviceBasicInfo](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md#devicebasicinfo)获得。 | 1058 1059**返回值:** 1060 1061 | 类型 | 说明 | 1062 | ------ | ---------------------------------------- | 1063 | Promise<void>| Promise对象。无返回值。 | 1064 1065**错误码:** 1066 1067接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1068 1069**示例:** 1070 1071 ```ts 1072 import { BusinessError } from '@kit.BasicServicesKit'; 1073 import { fileIo as fs } from '@kit.CoreFileKit'; 1074 import { distributedDeviceManager } from '@kit.DistributedServiceKit'; 1075 let dmInstance = distributedDeviceManager.createDeviceManager("com.example.filesync"); 1076 let deviceInfoList: Array<distributedDeviceManager.DeviceBasicInfo> = dmInstance.getAvailableDeviceListSync(); 1077 if (deviceInfoList && deviceInfoList.length > 0) { 1078 console.info(`Success to get available device list`); 1079 let networkId = deviceInfoList[0].networkId; 1080 fs.disconnectDfs(networkId).then(() => { 1081 console.info("Success to disconnect dfs"); 1082 }).catch((err: BusinessError) => { 1083 console.error(`Failed to disconnect dfs. Code: ${err.code}, message: ${err.message}`); 1084 }) 1085 } 1086 ``` 1087 1088## fs.setxattr<sup>12+</sup> 1089 1090setxattr(path: string, key: string, value: string): Promise<void> 1091 1092设置文件或目录的扩展属性。 1093 1094**系统能力**:SystemCapability.FileManagement.File.FileIO 1095 1096**参数:** 1097 1098| 参数名 | 类型 | 必填 | 说明 | 1099| ------ | ------ | ---- | ------------------------------------------------------------ | 1100| path | string | 是 | 文件或目录的应用沙箱路径。 | 1101| key | string | 是 | 扩展属性的key。仅支持前缀为“user.”的字符串,且长度需小于256字节。 | 1102| value | string | 是 | 扩展属性的value。 | 1103 1104**返回值:** 1105 1106 | 类型 | 说明 | 1107 | ------ | ---------------------------------------- | 1108 | Promise<void>| Promise对象。无返回值。 | 1109 1110**错误码:** 1111 1112接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1113 1114**示例:** 1115 1116 ```ts 1117 import { BusinessError } from '@kit.BasicServicesKit'; 1118 1119 let filePath = pathDir + "/test.txt"; 1120 let attrKey = "user.comment"; 1121 let attrValue = "Test file."; 1122 1123 fs.setxattr(filePath, attrKey, attrValue).then(() => { 1124 console.info("Set extended attribute successfully."); 1125 }).catch((err: BusinessError) => { 1126 console.error("Failed to set extended attribute with error message: " + err.message + ", error code: " + err.code); 1127 }); 1128 1129 ``` 1130## fs.setxattrSync<sup>12+</sup> 1131 1132setxattrSync(path: string, key: string, value: string): void 1133 1134设置文件或目录的扩展属性。 1135 1136**系统能力**:SystemCapability.FileManagement.File.FileIO 1137 1138**参数:** 1139 1140| 参数名 | 类型 | 必填 | 说明 | 1141| ------ | ------ | ---- | ------------------------------------------------------------ | 1142| path | string | 是 | 文件或目录的应用沙箱路径。 | 1143| key | string | 是 | 扩展属性的key。仅支持前缀为“user.”的字符串,且长度需小于256字节。 | 1144| value | string | 是 | 扩展属性的value。 | 1145 1146**错误码:** 1147 1148接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1149 1150**示例:** 1151 1152 ```ts 1153 import { BusinessError } from '@kit.BasicServicesKit'; 1154 1155 let filePath = pathDir + "/test.txt"; 1156 let attrKey = "user.comment"; 1157 let attrValue = "Test file."; 1158 1159 try { 1160 fs.setxattrSync(filePath, attrKey, attrValue); 1161 console.info("Set extended attribute successfully."); 1162 } catch (err) { 1163 console.error("Failed to set extended attribute with error message: " + err.message + ", error code: " + err.code); 1164 } 1165 1166 ``` 1167 1168## fs.getxattr<sup>12+</sup> 1169 1170getxattr(path: string, key: string): Promise<string> 1171 1172获取文件或目录的扩展属性。 1173 1174**系统能力**:SystemCapability.FileManagement.File.FileIO 1175 1176**参数:** 1177 1178| 参数名 | 类型 | 必填 | 说明 | 1179| ------ | ------ | ---- | ------------------------------------------------------------ | 1180| path | string | 是 | 文件或目录的应用沙箱路径。 | 1181| key | string | 是 | 扩展属性的key。 | 1182 1183**返回值:** 1184 1185 | 类型 | 说明 | 1186 | ------ | ---------------------------------------- | 1187 | Promise<string>| Promise对象。返回扩展属性的value。 | 1188 1189**错误码:** 1190 1191接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1192 1193**示例:** 1194 1195 ```ts 1196 import { BusinessError } from '@kit.BasicServicesKit'; 1197 1198 let filePath = pathDir + "/test.txt"; 1199 let attrKey = "user.comment"; 1200 1201 fs.getxattr(filePath, attrKey).then((attrValue: string) => { 1202 console.info("Get extended attribute succeed, the value is: " + attrValue); 1203 }).catch((err: BusinessError) => { 1204 console.error("Failed to get extended attribute with error message: " + err.message + ", error code: " + err.code); 1205 }); 1206 1207 ``` 1208 1209## fs.getxattrSync<sup>12+</sup> 1210 1211getxattrSync(path: string, key: string): string 1212 1213使用同步接口获取文件或目录的扩展属性。 1214 1215**系统能力**:SystemCapability.FileManagement.File.FileIO 1216 1217**参数:** 1218 1219| 参数名 | 类型 | 必填 | 说明 | 1220| ------ | ------ | ---- | ------------------------------------------------------------ | 1221| path | string | 是 | 文件或目录的应用沙箱路径。 | 1222| key | string | 是 | 扩展属性的key。 | 1223 1224**返回值:** 1225 1226 | 类型 | 说明 | 1227 | ------ | ------------------- | 1228 | string | 返回扩展属性的value。| 1229 1230**错误码:** 1231 1232接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1233 1234**示例:** 1235 1236 ```ts 1237 import { BusinessError } from '@kit.BasicServicesKit'; 1238 1239 let filePath = pathDir + "/test.txt"; 1240 let attrKey = "user.comment"; 1241 1242 try { 1243 let attrValue = fs.getxattrSync(filePath, attrKey); 1244 console.info("Get extended attribute succeed, the value is: " + attrValue); 1245 } catch (err) { 1246 console.error("Failed to get extended attribute with error message: " + err.message + ", error code: " + err.code); 1247 } 1248 1249 ``` 1250 1251## fs.mkdir 1252 1253mkdir(path: string): Promise<void> 1254 1255创建目录,使用promise异步回调。 1256 1257**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1258 1259**系统能力**:SystemCapability.FileManagement.File.FileIO 1260 1261**参数:** 1262 1263| 参数名 | 类型 | 必填 | 说明 | 1264| ------ | ------ | ---- | ------------------------------------------------------------ | 1265| path | string | 是 | 目录的应用沙箱路径。 | 1266 1267**返回值:** 1268 1269 | 类型 | 说明 | 1270 | ------------------- | ---------------------------- | 1271 | Promise<void> | Promise对象。无返回值。 | 1272 1273**错误码:** 1274 1275接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1276 1277**示例:** 1278 1279 ```ts 1280 import { BusinessError } from '@kit.BasicServicesKit'; 1281 let dirPath = pathDir + "/testDir"; 1282 fs.mkdir(dirPath).then(() => { 1283 console.info("mkdir succeed"); 1284 }).catch((err: BusinessError) => { 1285 console.error("mkdir failed with error message: " + err.message + ", error code: " + err.code); 1286 }); 1287 ``` 1288 1289## fs.mkdir<sup>11+</sup> 1290 1291mkdir(path: string, recursion: boolean): Promise\<void> 1292 1293创建目录,使用promise异步回调。当recursion指定为true时,可递归创建目录。 1294 1295**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1296 1297**系统能力**:SystemCapability.FileManagement.File.FileIO 1298 1299**参数:** 1300 1301| 参数名 | 类型 | 必填 | 说明 | 1302| ------ | ------ | ---- | ------------------------------------------------------------ | 1303| path | string | 是 | 目录的应用沙箱路径。 | 1304| recursion | boolean | 是 | 是否递归创建目录。recursion指定为true时,可递归创建目录。recursion指定为false时,仅可创建单层目录。 | 1305 1306**返回值:** 1307 1308 | 类型 | 说明 | 1309 | ------------------- | ---------------------------- | 1310 | Promise<void> | Promise对象。无返回值。 | 1311 1312**错误码:** 1313 1314接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1315 1316**示例:** 1317 1318 ```ts 1319 import { BusinessError } from '@kit.BasicServicesKit'; 1320 let dirPath = pathDir + "/testDir1/testDir2/testDir3"; 1321 fs.mkdir(dirPath, true).then(() => { 1322 console.info("mkdir succeed"); 1323 }).catch((err: BusinessError) => { 1324 console.error("mkdir failed with error message: " + err.message + ", error code: " + err.code); 1325 }); 1326 ``` 1327 1328## fs.mkdir 1329 1330mkdir(path: string, callback: AsyncCallback<void>): void 1331 1332创建目录,使用callback异步回调。 1333 1334**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1335 1336**系统能力**:SystemCapability.FileManagement.File.FileIO 1337 1338**参数:** 1339 1340| 参数名 | 类型 | 必填 | 说明 | 1341| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 1342| path | string | 是 | 目录的应用沙箱路径。 | 1343| callback | AsyncCallback<void> | 是 | 异步创建目录操作完成之后的回调。 | 1344 1345**错误码:** 1346 1347接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1348 1349**示例:** 1350 1351 ```ts 1352 import { BusinessError } from '@kit.BasicServicesKit'; 1353 let dirPath = pathDir + "/testDir"; 1354 fs.mkdir(dirPath, (err: BusinessError) => { 1355 if (err) { 1356 console.error("mkdir failed with error message: " + err.message + ", error code: " + err.code); 1357 } else { 1358 console.info("mkdir succeed"); 1359 } 1360 }); 1361 ``` 1362 1363## fs.mkdir<sup>11+</sup> 1364 1365mkdir(path: string, recursion: boolean, callback: AsyncCallback<void>): void 1366 1367创建目录,使用callback异步回调。当recursion指定为true,可递归创建目录。 1368 1369**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1370 1371**系统能力**:SystemCapability.FileManagement.File.FileIO 1372 1373**参数:** 1374 1375| 参数名 | 类型 | 必填 | 说明 | 1376| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 1377| path | string | 是 | 目录的应用沙箱路径。 | 1378| recursion | boolean | 是 | 是否递归创建目录。recursion指定为true时,可递归创建目录。recursion指定为false时,仅可创建单层目录。 | 1379| callback | AsyncCallback<void> | 是 | 异步创建目录操作完成之后的回调。 | 1380 1381**错误码:** 1382 1383接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1384 1385**示例:** 1386 1387 ```ts 1388 import { BusinessError } from '@kit.BasicServicesKit'; 1389 let dirPath = pathDir + "/testDir1/testDir2/testDir3"; 1390 fs.mkdir(dirPath, true, (err: BusinessError) => { 1391 if (err) { 1392 console.error("mkdir failed with error message: " + err.message + ", error code: " + err.code); 1393 } else { 1394 console.info("mkdir succeed"); 1395 } 1396 }); 1397 ``` 1398 1399## fs.mkdirSync 1400 1401mkdirSync(path: string): void 1402 1403以同步方法创建目录。 1404 1405**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1406 1407**系统能力**:SystemCapability.FileManagement.File.FileIO 1408 1409**参数:** 1410 1411| 参数名 | 类型 | 必填 | 说明 | 1412| ------ | ------ | ---- | ------------------------------------------------------------ | 1413| path | string | 是 | 目录的应用沙箱路径。 | 1414 1415**错误码:** 1416 1417接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1418 1419**示例:** 1420 1421 ```ts 1422 let dirPath = pathDir + "/testDir"; 1423 fs.mkdirSync(dirPath); 1424 ``` 1425 1426## fs.mkdirSync<sup>11+</sup> 1427 1428mkdirSync(path: string, recursion: boolean): void 1429 1430以同步方法创建目录。当recursion指定为true,可递归创建目录。 1431 1432**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1433 1434**系统能力**:SystemCapability.FileManagement.File.FileIO 1435 1436**参数:** 1437 1438| 参数名 | 类型 | 必填 | 说明 | 1439| ------ | ------ | ---- | ------------------------------------------------------------ | 1440| path | string | 是 | 目录的应用沙箱路径。 | 1441| recursion | boolean | 是 | 是否递归创建目录。recursion指定为true时,可递归创建目录。recursion指定为false时,仅可创建单层目录。 | 1442 1443**错误码:** 1444 1445接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1446 1447**示例:** 1448 1449 ```ts 1450 let dirPath = pathDir + "/testDir1/testDir2/testDir3"; 1451 fs.mkdirSync(dirPath, true); 1452 ``` 1453 1454## fs.open 1455 1456open(path: string, mode?: number): Promise<File> 1457 1458打开文件或目录,使用promise异步回调。支持使用URI打开文件。 1459 1460**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1461 1462**系统能力**:SystemCapability.FileManagement.File.FileIO 1463 1464**参数:** 1465 1466| 参数名 | 类型 | 必填 | 说明 | 1467| ------ | ------ | ---- | ------------------------------------------------------------ | 1468| path | string | 是 | 文件或目录的应用沙箱路径或文件URI。 | 1469| mode | number | 否 | 打开文件或目录的[选项](#openmode),必须指定如下选项中的一个,默认以只读方式打开:<br/>- OpenMode.READ_ONLY(0o0):只读打开。<br/>- OpenMode.WRITE_ONLY(0o1):只写打开。<br/>- OpenMode.READ_WRITE(0o2):读写打开。<br/>可以追加以下功能选项,以按位或的方式组合,默认情况下不追加任何额外选项。<br/>- OpenMode.CREATE(0o100):如果文件不存在,则创建文件。<br/>- OpenMode.TRUNC(0o1000):如果文件存在且文件具有写权限,则将其长度裁剪为零。<br/>- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到文件末尾。<br/>- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。<br/>- OpenMode.DIR(0o200000):如果path不指向目录,则出错。不允许附加写权限。<br/>- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。<br/>- OpenMode.SYNC(0o4010000):以同步IO方式打开文件。 | 1470 1471**返回值:** 1472 1473 | 类型 | 说明 | 1474 | --------------------- | ----------- | 1475 | Promise<[File](#file)> | Promise对象。返回File对象。 | 1476 1477**错误码:** 1478 1479接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1480 1481**示例:** 1482 1483 ```ts 1484 import { BusinessError } from '@kit.BasicServicesKit'; 1485 let filePath = pathDir + "/test.txt"; 1486 fs.open(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE).then((file: fs.File) => { 1487 console.info("file fd: " + file.fd); 1488 fs.closeSync(file); 1489 }).catch((err: BusinessError) => { 1490 console.error("open file failed with error message: " + err.message + ", error code: " + err.code); 1491 }); 1492 ``` 1493 1494 1495## fs.open 1496 1497open(path: string, mode: number, callback: AsyncCallback<File>): void 1498 1499打开文件或目录,可设置打开文件的选项。使用callback异步回调。 1500 1501支持使用URI打开文件。 1502 1503**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1504 1505**系统能力**:SystemCapability.FileManagement.File.FileIO 1506 1507**参数:** 1508 1509| 参数名 | 类型 | 必填 | 说明 | 1510| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | 1511| path | string | 是 | 文件或目录的应用沙箱路径或URI。 | 1512| mode | number | 是 | 打开文件或目录的[选项](#openmode),必须指定如下选项中的一个,默认以只读方式打开:<br/>- OpenMode.READ_ONLY(0o0):只读打开。<br/>- OpenMode.WRITE_ONLY(0o1):只写打开。<br/>- OpenMode.READ_WRITE(0o2):读写打开。<br/>给定如下功能选项,以按位或的方式追加,默认不给定任何额外选项:<br/>- OpenMode.CREATE(0o100):若文件不存在,则创建文件。<br/>- OpenMode.TRUNC(0o1000):如果文件存在且文件具有写权限,则将其长度裁剪为零。<br/>- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到文件末尾。<br/>- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。<br/>- OpenMode.DIR(0o200000):如果path不指向目录,则出错。不允许附加写权限。<br/>- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。<br/>- OpenMode.SYNC(0o4010000):以同步IO的方式打开文件。 | 1513| callback | AsyncCallback<void> | 是 | 异步打开文件之后的回调。 | 1514 1515**错误码:** 1516 1517接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1518 1519**示例:** 1520 1521 ```ts 1522 import { BusinessError } from '@kit.BasicServicesKit'; 1523 let filePath = pathDir + "/test.txt"; 1524 fs.open(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE, (err: BusinessError, file: fs.File) => { 1525 if (err) { 1526 console.error("open failed with error message: " + err.message + ", error code: " + err.code); 1527 } else { 1528 console.info("file fd: " + file.fd); 1529 fs.closeSync(file); 1530 } 1531 }); 1532 ``` 1533 1534## fs.open 1535 1536open(path: string, callback: AsyncCallback<File>): void 1537 1538打开文件或目录,使用callback异步回调。支持使用URI打开文件。 1539 1540**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1541 1542**系统能力**:SystemCapability.FileManagement.File.FileIO 1543 1544**参数:** 1545 1546| 参数名 | 类型 | 必填 | 说明 | 1547| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | 1548| path | string | 是 | 文件或目录的应用沙箱路径或URI。 | 1549| callback | AsyncCallback<void> | 是 | 异步打开文件之后的回调。 | 1550 1551**错误码:** 1552 1553接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1554 1555**示例:** 1556 1557 ```ts 1558 import { BusinessError } from '@kit.BasicServicesKit'; 1559 let filePath = pathDir + "/test.txt"; 1560 fs.open(filePath, (err: BusinessError, file: fs.File) => { 1561 if (err) { 1562 console.error("open failed with error message: " + err.message + ", error code: " + err.code); 1563 } else { 1564 console.info("file fd: " + file.fd); 1565 fs.closeSync(file); 1566 } 1567 }); 1568 ``` 1569 1570## fs.openSync 1571 1572openSync(path: string, mode?: number): File 1573 1574以同步方法打开文件或目录。支持使用URI打开文件。 1575 1576**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1577 1578**系统能力**:SystemCapability.FileManagement.File.FileIO 1579 1580**参数:** 1581 1582| 参数名 | 类型 | 必填 | 说明 | 1583| ------ | ------ | ---- | ------------------------------------------------------------ | 1584| path | string | 是 | 打开文件或目录的应用沙箱路径或URI。 | 1585| mode | number | 否 | 打开文件或目录的[选项](#openmode),必须指定如下选项中的一个,默认以只读方式打开:<br/>- OpenMode.READ_ONLY(0o0):只读打开。<br/>- OpenMode.WRITE_ONLY(0o1):只写打开。<br/>- OpenMode.READ_WRITE(0o2):读写打开。<br/>给定如下功能选项,以按位或的方式追加,默认不给定任何额外选项:<br/>- OpenMode.CREATE(0o100):若文件不存在,则创建文件。<br/>- OpenMode.TRUNC(0o1000):如果文件存在且文件具有写权限,则将其长度裁剪为零。<br/>- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到文件末尾。<br/>- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。<br/>- OpenMode.DIR(0o200000):如果path不指向目录,则出错。不允许附加写权限。<br/>- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。<br/>- OpenMode.SYNC(0o4010000):以同步IO的方式打开文件。 | 1586 1587**返回值:** 1588 1589 | 类型 | 说明 | 1590 | ------ | ----------- | 1591 | [File](#file) | 打开的File对象。 | 1592 1593**错误码:** 1594 1595接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1596 1597**示例:** 1598 1599 ```ts 1600 let filePath = pathDir + "/test.txt"; 1601 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 1602 console.info("file fd: " + file.fd); 1603 fs.closeSync(file); 1604 ``` 1605 1606## fs.read 1607 1608read(fd: number, buffer: ArrayBuffer, options?: ReadOptions): Promise<number> 1609 1610读取文件数据,使用promise异步回调。 1611 1612**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1613 1614**系统能力**:SystemCapability.FileManagement.File.FileIO 1615 1616**参数:** 1617 1618| 参数名 | 类型 | 必填 | 说明 | 1619| ------- | ----------- | ---- | ------------------------------------------------------------ | 1620| fd | number | 是 | 已打开的文件描述符。 | 1621| buffer | ArrayBuffer | 是 | 用于保存读取到的文件数据的缓冲区。 | 1622| options | [ReadOptions](#readoptions11) | 否 | 支持如下选项:<br/>- offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读。<br/>- length,number类型,表示期望读取数据的长度。可选,默认缓冲区长度。| 1623 1624**返回值:** 1625 1626 | 类型 | 说明 | 1627 | ---------------------------------- | ------ | 1628 | Promise<number> | Promise对象。返回实际读取的数据长度(单位:字节)。| 1629 1630**错误码:** 1631 1632接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1633 1634**示例:** 1635 1636 ```ts 1637 import { BusinessError } from '@kit.BasicServicesKit'; 1638 import { buffer } from '@kit.ArkTS'; 1639 let filePath = pathDir + "/test.txt"; 1640 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); 1641 let arrayBuffer = new ArrayBuffer(4096); 1642 fs.read(file.fd, arrayBuffer).then((readLen: number) => { 1643 console.info("read file data succeed"); 1644 let buf = buffer.from(arrayBuffer, 0, readLen); 1645 console.info(`The content of file: ${buf.toString()}`); 1646 }).catch((err: BusinessError) => { 1647 console.error("read file data failed with error message: " + err.message + ", error code: " + err.code); 1648 }).finally(() => { 1649 fs.closeSync(file); 1650 }); 1651 ``` 1652 1653## fs.read 1654 1655read(fd: number, buffer: ArrayBuffer, options?: ReadOptions, callback: AsyncCallback<number>): void 1656 1657从文件读取数据,使用callback异步回调。 1658 1659**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1660 1661**系统能力**:SystemCapability.FileManagement.File.FileIO 1662 1663**参数:** 1664 1665 | 参数名 | 类型 | 必填 | 说明 | 1666 | -------- | ---------------------------------------- | ---- | ---------------------------------------- | 1667 | fd | number | 是 | 已打开的文件描述符。 | 1668 | buffer | ArrayBuffer | 是 | 用于保存读取到的文件数据的缓冲区。 | 1669 | options | [ReadOptions](#readoptions11) | 否 | 支持如下选项:<br/>- offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读。<br/>- length,number类型,表示期望读取数据的长度。可选,默认缓冲区长度。| 1670 | callback | AsyncCallback<number> | 是 | 异步读取数据之后的回调。返回实际读取的数据长度,单位字节。 | 1671 1672**错误码:** 1673 1674接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1675 1676**示例:** 1677 1678 ```ts 1679 import { BusinessError } from '@kit.BasicServicesKit'; 1680 import { buffer } from '@kit.ArkTS'; 1681 let filePath = pathDir + "/test.txt"; 1682 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); 1683 let arrayBuffer = new ArrayBuffer(4096); 1684 fs.read(file.fd, arrayBuffer, (err: BusinessError, readLen: number) => { 1685 if (err) { 1686 console.error("read failed with error message: " + err.message + ", error code: " + err.code); 1687 } else { 1688 console.info("read file data succeed"); 1689 let buf = buffer.from(arrayBuffer, 0, readLen); 1690 console.info(`The content of file: ${buf.toString()}`); 1691 } 1692 fs.closeSync(file); 1693 }); 1694 ``` 1695 1696## fs.readSync 1697 1698readSync(fd: number, buffer: ArrayBuffer, options?: ReadOptions): number 1699 1700以同步方法从文件读取数据。 1701 1702**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1703 1704**系统能力**:SystemCapability.FileManagement.File.FileIO 1705 1706**参数:** 1707 1708 | 参数名 | 类型 | 必填 | 说明 | 1709 | ------- | ----------- | ---- | ---------------------------------------- | 1710 | fd | number | 是 | 已打开的文件描述符。 | 1711 | buffer | ArrayBuffer | 是 | 用于保存读取到的文件数据的缓冲区。 | 1712 | options | [ReadOptions](#readoptions11) | 否 | 支持如下选项:<br/>- offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读。<br/>- length,number类型,表示期望读取数据的长度。可选,默认缓冲区长度。| 1713 1714**返回值:** 1715 1716 | 类型 | 说明 | 1717 | ------ | -------- | 1718 | number | 返回实际读取的数据长度(单位:字节)。 | 1719 1720**错误码:** 1721 1722接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1723 1724**示例:** 1725 1726 ```ts 1727 let filePath = pathDir + "/test.txt"; 1728 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); 1729 let buf = new ArrayBuffer(4096); 1730 fs.readSync(file.fd, buf); 1731 fs.closeSync(file); 1732 ``` 1733 1734## fs.rmdir 1735 1736rmdir(path: string): Promise<void> 1737 1738删除目录及其所有子目录和文件,使用promise异步回调。 1739 1740> **说明:** 1741> 1742> 该接口支持删除单个文件,但不推荐使用此方法删除单个文件,推荐使用unlink接口删除单个文件。 1743 1744**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1745 1746**系统能力**:SystemCapability.FileManagement.File.FileIO 1747 1748**参数:** 1749 1750| 参数名 | 类型 | 必填 | 说明 | 1751| ------ | ------ | ---- | -------------------------- | 1752| path | string | 是 | 目录的应用沙箱路径。 | 1753 1754**返回值:** 1755 1756 | 类型 | 说明 | 1757 | ------------------- | ---------------------------- | 1758 | Promise<void> | Promise对象。无返回值。 | 1759 1760**错误码:** 1761 1762接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1763 1764**示例:** 1765 1766 ```ts 1767 import { BusinessError } from '@kit.BasicServicesKit'; 1768 let dirPath = pathDir + "/testDir"; 1769 fs.rmdir(dirPath).then(() => { 1770 console.info("rmdir succeed"); 1771 }).catch((err: BusinessError) => { 1772 console.error("rmdir failed with error message: " + err.message + ", error code: " + err.code); 1773 }); 1774 ``` 1775 1776## fs.rmdir 1777 1778rmdir(path: string, callback: AsyncCallback<void>): void 1779 1780删除目录及其所有子目录和文件,使用callback异步回调。 1781 1782> **说明:** 1783> 1784> 该接口支持删除单个文件,但不推荐使用此方法删除单个文件,推荐使用unlink接口删除单个文件。 1785 1786**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1787 1788**系统能力**:SystemCapability.FileManagement.File.FileIO 1789 1790**参数:** 1791 1792| 参数名 | 类型 | 必填 | 说明 | 1793| -------- | ------------------------- | ---- | -------------------------- | 1794| path | string | 是 | 目录的应用沙箱路径。 | 1795| callback | AsyncCallback<void> | 是 | 异步删除目录之后的回调。 | 1796 1797**错误码:** 1798 1799接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1800 1801**示例:** 1802 1803 ```ts 1804 import { BusinessError } from '@kit.BasicServicesKit'; 1805 let dirPath = pathDir + "/testDir"; 1806 fs.rmdir(dirPath, (err: BusinessError) => { 1807 if (err) { 1808 console.error("rmdir failed with error message: " + err.message + ", error code: " + err.code); 1809 } else { 1810 console.info("rmdir succeed"); 1811 } 1812 }); 1813 ``` 1814 1815## fs.rmdirSync 1816 1817rmdirSync(path: string): void 1818 1819以同步方法删除目录及其所有子目录和文件。 1820 1821> **说明:** 1822> 1823> 该接口支持删除单个文件,但不推荐使用此方法删除单个文件,推荐使用unlinkSync接口删除单个文件。 1824 1825**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1826 1827**系统能力**:SystemCapability.FileManagement.File.FileIO 1828 1829**参数:** 1830 1831| 参数名 | 类型 | 必填 | 说明 | 1832| ------ | ------ | ---- | -------------------------- | 1833| path | string | 是 | 目录的应用沙箱路径。 | 1834 1835**错误码:** 1836 1837接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1838 1839**示例:** 1840 1841 ```ts 1842 let dirPath = pathDir + "/testDir"; 1843 fs.rmdirSync(dirPath); 1844 ``` 1845 1846## fs.unlink 1847 1848unlink(path: string): Promise<void> 1849 1850删除单个文件,使用promise异步回调。 1851 1852**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1853 1854**系统能力**:SystemCapability.FileManagement.File.FileIO 1855 1856**参数:** 1857 1858| 参数名 | 类型 | 必填 | 说明 | 1859| ------ | ------ | ---- | -------------------------- | 1860| path | string | 是 | 文件的应用沙箱路径。 | 1861 1862**返回值:** 1863 1864 | 类型 | 说明 | 1865 | ------------------- | ---------------------------- | 1866 | Promise<void> | Promise对象。无返回值。 | 1867 1868**错误码:** 1869 1870接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1871 1872**示例:** 1873 1874 ```ts 1875 import { BusinessError } from '@kit.BasicServicesKit'; 1876 let filePath = pathDir + "/test.txt"; 1877 fs.unlink(filePath).then(() => { 1878 console.info("remove file succeed"); 1879 }).catch((err: BusinessError) => { 1880 console.error("remove file failed with error message: " + err.message + ", error code: " + err.code); 1881 }); 1882 ``` 1883 1884## fs.unlink 1885 1886unlink(path: string, callback: AsyncCallback<void>): void 1887 1888删除文件,使用callback异步回调。 1889 1890**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1891 1892**系统能力**:SystemCapability.FileManagement.File.FileIO 1893 1894**参数:** 1895 1896| 参数名 | 类型 | 必填 | 说明 | 1897| -------- | ------------------------- | ---- | -------------------------- | 1898| path | string | 是 | 文件的应用沙箱路径。 | 1899| callback | AsyncCallback<void> | 是 | 异步删除文件之后的回调。 | 1900 1901**错误码:** 1902 1903接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1904 1905**示例:** 1906 1907 ```ts 1908 import { BusinessError } from '@kit.BasicServicesKit'; 1909 let filePath = pathDir + "/test.txt"; 1910 fs.unlink(filePath, (err: BusinessError) => { 1911 if (err) { 1912 console.error("remove file failed with error message: " + err.message + ", error code: " + err.code); 1913 } else { 1914 console.info("remove file succeed"); 1915 } 1916 }); 1917 ``` 1918 1919## fs.unlinkSync 1920 1921unlinkSync(path: string): void 1922 1923以同步方法删除文件。 1924 1925**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1926 1927**系统能力**:SystemCapability.FileManagement.File.FileIO 1928 1929**参数:** 1930 1931| 参数名 | 类型 | 必填 | 说明 | 1932| ------ | ------ | ---- | -------------------------- | 1933| path | string | 是 | 文件的应用沙箱路径。 | 1934 1935**错误码:** 1936 1937接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1938 1939**示例:** 1940 1941 ```ts 1942 let filePath = pathDir + "/test.txt"; 1943 fs.unlinkSync(filePath); 1944 ``` 1945 1946 1947## fs.write 1948 1949write(fd: number, buffer: ArrayBuffer | string, options?: WriteOptions): Promise<number> 1950 1951将数据写入文件,使用promise异步回调。 1952 1953**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1954 1955**系统能力**:SystemCapability.FileManagement.File.FileIO 1956 1957**参数:** 1958 1959 | 参数名 | 类型 | 必填 | 说明 | 1960 | ------- | ------------------------------- | ---- | ---------------------------------------- | 1961 | fd | number | 是 | 已打开的文件描述符。 | 1962 | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | 1963 | options | [WriteOptions](#writeoptions11) | 否 | 支持如下选项:<br/>- offset,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写入。<br/>- length,number类型,表示期望写入数据的长度。可选,默认缓冲区长度。<br/>- encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 'utf-8'。当前仅支持 'utf-8'。| 1964 1965**返回值:** 1966 1967 | 类型 | 说明 | 1968 | --------------------- | -------- | 1969 | Promise<number> | Promise对象。返回实际写入的数据长度(单位:字节)。 | 1970 1971**错误码:** 1972 1973接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1974 1975**示例:** 1976 1977 ```ts 1978 import { BusinessError } from '@kit.BasicServicesKit'; 1979 let filePath = pathDir + "/test.txt"; 1980 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 1981 let str: string = "hello, world"; 1982 fs.write(file.fd, str).then((writeLen: number) => { 1983 console.info("write data to file succeed and size is:" + writeLen); 1984 }).catch((err: BusinessError) => { 1985 console.error("write data to file failed with error message: " + err.message + ", error code: " + err.code); 1986 }).finally(() => { 1987 fs.closeSync(file); 1988 }); 1989 ``` 1990 1991## fs.write 1992 1993write(fd: number, buffer: ArrayBuffer | string, options?: WriteOptions, callback: AsyncCallback<number>): void 1994 1995将数据写入文件,使用callback异步回调。 1996 1997**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1998 1999**系统能力**:SystemCapability.FileManagement.File.FileIO 2000 2001**参数:** 2002 2003 | 参数名 | 类型 | 必填 | 说明 | 2004 | -------- | ------------------------------- | ---- | ---------------------------------------- | 2005 | fd | number | 是 | 已打开的文件描述符。 | 2006 | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | 2007 | options | [WriteOptions](#writeoptions11) | 否 | 支持如下选项:<br/>- offset,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写。<br/>- length,number类型,表示期望写入数据的长度。可选,默认缓冲区长度。<br/>- encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 'utf-8'。当前仅支持 'utf-8'。| 2008 | callback | AsyncCallback<number> | 是 | 异步将数据写入完成后执行的回调函数。 | 2009 2010**错误码:** 2011 2012接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2013 2014**示例:** 2015 2016 ```ts 2017 import { BusinessError } from '@kit.BasicServicesKit'; 2018 let filePath = pathDir + "/test.txt"; 2019 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 2020 let str: string = "hello, world"; 2021 fs.write(file.fd, str, (err: BusinessError, writeLen: number) => { 2022 if (err) { 2023 console.error("write data to file failed with error message:" + err.message + ", error code: " + err.code); 2024 } else { 2025 console.info("write data to file succeed and size is:" + writeLen); 2026 } 2027 fs.closeSync(file); 2028 }); 2029 ``` 2030 2031## fs.writeSync 2032 2033writeSync(fd: number, buffer: ArrayBuffer | string, options?: WriteOptions): number 2034 2035以同步方法将数据写入文件。 2036 2037**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 2038 2039**系统能力**:SystemCapability.FileManagement.File.FileIO 2040 2041**参数:** 2042 2043 | 参数名 | 类型 | 必填 | 说明 | 2044 | ------- | ------------------------------- | ---- | ---------------------------------------- | 2045 | fd | number | 是 | 已打开的文件描述符。 | 2046 | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | 2047 | options | [WriteOptions](#writeoptions11) | 否 | 支持如下选项:<br/>- offset,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写。<br/>- length,number类型,表示期望写入数据的长度。可选,默认缓冲区长度。<br/>- encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 'utf-8'。当前仅支持 'utf-8'。| 2048 2049**返回值:** 2050 2051 | 类型 | 说明 | 2052 | ------ | -------- | 2053 | number | 返回实际写入的数据长度(单位:字节)。 | 2054 2055**错误码:** 2056 2057接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2058 2059**示例:** 2060 2061 ```ts 2062 let filePath = pathDir + "/test.txt"; 2063 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 2064 let str: string = "hello, world"; 2065 let writeLen = fs.writeSync(file.fd, str); 2066 console.info("write data to file succeed and size is:" + writeLen); 2067 fs.closeSync(file); 2068 ``` 2069 2070## fs.truncate 2071 2072truncate(file: string | number, len?: number): Promise<void> 2073 2074截断文件,使用promise异步回调。 2075 2076**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 2077 2078**系统能力**:SystemCapability.FileManagement.File.FileIO 2079 2080**参数:** 2081 2082| 参数名 | 类型 | 必填 | 说明 | 2083| ------ | ------ | ---- | -------------------------------- | 2084| file | string \| number | 是 | 文件的应用沙箱路径或已打开的文件描述符fd。 | 2085| len | number | 否 | 文件截断后的长度(单位:字节)。默认为0。 | 2086 2087**返回值:** 2088 2089 | 类型 | 说明 | 2090 | ------------------- | ---------------------------- | 2091 | Promise<void> | Promise对象。无返回值。 | 2092 2093**错误码:** 2094 2095接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2096 2097**示例:** 2098 2099 ```ts 2100 import { BusinessError } from '@kit.BasicServicesKit'; 2101 let filePath = pathDir + "/test.txt"; 2102 let len: number = 5; 2103 fs.truncate(filePath, len).then(() => { 2104 console.info("truncate file succeed"); 2105 }).catch((err: BusinessError) => { 2106 console.error("truncate file failed with error message: " + err.message + ", error code: " + err.code); 2107 }); 2108 ``` 2109 2110## fs.truncate 2111 2112truncate(file: string | number, len?: number, callback: AsyncCallback<void>): void 2113 2114截断文件,使用callback异步回调。 2115 2116**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 2117 2118**系统能力**:SystemCapability.FileManagement.File.FileIO 2119 2120**参数:** 2121 2122| 参数名 | 类型 | 必填 | 说明 | 2123| -------- | ------------------------- | ---- | -------------------------------- | 2124| file | string \| number | 是 | 文件的应用沙箱路径或已打开的文件描述符fd。 | 2125| len | number | 否 | 文件截断后的长度,以字节为单位。默认为0。 | 2126| callback | AsyncCallback<void> | 是 | 回调函数,本调用无返回值。 | 2127 2128**错误码:** 2129 2130接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2131 2132**示例:** 2133 2134 ```ts 2135 import { BusinessError } from '@kit.BasicServicesKit'; 2136 let filePath = pathDir + "/test.txt"; 2137 let len: number = 5; 2138 fs.truncate(filePath, len, (err: BusinessError) => { 2139 if (err) { 2140 console.error("truncate failed with error message: " + err.message + ", error code: " + err.code); 2141 } else { 2142 console.info("truncate succeed"); 2143 } 2144 }); 2145 ``` 2146 2147## fs.truncateSync 2148 2149truncateSync(file: string | number, len?: number): void 2150 2151以同步方法截断文件内容。 2152 2153**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 2154 2155**系统能力**:SystemCapability.FileManagement.File.FileIO 2156 2157**参数:** 2158 2159| 参数名 | 类型 | 必填 | 说明 | 2160| ------ | ------ | ---- | -------------------------------- | 2161| file | string \| number | 是 | 文件的应用沙箱路径或已打开的文件描述符fd。 | 2162| len | number | 否 | 文件截断后的长度(单位:字节)。默认为0。 | 2163 2164**错误码:** 2165 2166接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2167 2168**示例:** 2169 2170 ```ts 2171 let filePath = pathDir + "/test.txt"; 2172 let len: number = 5; 2173 fs.truncateSync(filePath, len); 2174 ``` 2175 2176## fs.readLines<sup>11+</sup> 2177 2178readLines(filePath: string, options?: Options): Promise<ReaderIterator> 2179 2180逐行读取文件文本内容,使用promise异步回调。只支持读取utf-8格式文件。 2181 2182**系统能力**:SystemCapability.FileManagement.File.FileIO 2183 2184**参数:** 2185 2186| 参数名 | 类型 | 必填 | 说明 | 2187| -------- | ------ | ---- | ------------------------------------------------------------ | 2188| filePath | string | 是 | 文件的应用沙箱路径。 | 2189| options | [Options](#options11) | 否 | 可选项。支持以下选项:<br/>- encoding,string类型,当数据是 string 类型时有效,表示数据的编码方式,默认 'utf-8',仅支持 'utf-8'。| 2190 2191**返回值:** 2192 2193 | 类型 | 说明 | 2194 | --------------------- | ---------- | 2195 | Promise<[ReaderIterator](#readeriterator11)> | Promise对象。返回文件读取迭代器。 | 2196 2197**错误码:** 2198 2199接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2200 2201**示例:** 2202 2203 ```ts 2204 import { BusinessError } from '@kit.BasicServicesKit'; 2205 import { fileIo as fs, Options } from '@kit.CoreFileKit'; 2206 let filePath = pathDir + "/test.txt"; 2207 let options: Options = { 2208 encoding: 'utf-8' 2209 }; 2210 fs.readLines(filePath, options).then((readerIterator: fs.ReaderIterator) => { 2211 for (let it = readerIterator.next(); !it.done; it = readerIterator.next()) { 2212 console.info("content: " + it.value); 2213 } 2214 }).catch((err: BusinessError) => { 2215 console.error("readLines failed with error message: " + err.message + ", error code: " + err.code); 2216 }); 2217 ``` 2218 2219## fs.readLines<sup>11+</sup> 2220 2221readLines(filePath: string, options?: Options, callback: AsyncCallback<ReaderIterator>): void 2222 2223逐行读取文件文本内容,使用callback异步回调,只支持读取utf-8格式文件。 2224 2225**系统能力**:SystemCapability.FileManagement.File.FileIO 2226 2227**参数:** 2228 2229| 参数名 | 类型 | 必填 | 说明 | 2230| -------- | ------ | ---- | ------------------------------------------------------------ | 2231| filePath | string | 是 | 文件的应用沙箱路径。 | 2232| options | [Options](#options11) | 否 | 可选项。支持以下选项:<br/>- encoding,string类型,当数据是 string 类型时有效,表示数据的编码方式,默认 'utf-8',仅支持 'utf-8'。| 2233| callback | AsyncCallback<[ReaderIterator](#readeriterator11)> | 是 | 逐行读取文件文本内容回调。 | 2234 2235**错误码:** 2236 2237接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2238 2239**示例:** 2240 2241 ```ts 2242 import { BusinessError } from '@kit.BasicServicesKit'; 2243 import { fileIo as fs, Options } from '@kit.CoreFileKit'; 2244 let filePath = pathDir + "/test.txt"; 2245 let options: Options = { 2246 encoding: 'utf-8' 2247 }; 2248 fs.readLines(filePath, options, (err: BusinessError, readerIterator: fs.ReaderIterator) => { 2249 if (err) { 2250 console.error("readLines failed with error message: " + err.message + ", error code: " + err.code); 2251 } else { 2252 for (let it = readerIterator.next(); !it.done; it = readerIterator.next()) { 2253 console.info("content: " + it.value); 2254 } 2255 } 2256 }); 2257 ``` 2258 2259## fs.readLinesSync<sup>11+</sup> 2260 2261readLinesSync(filePath: string, options?: Options): ReaderIterator 2262 2263以同步方式逐行读取文件的文本内容。 2264 2265**系统能力**:SystemCapability.FileManagement.File.FileIO 2266 2267**参数:** 2268 2269| 参数名 | 类型 | 必填 | 说明 | 2270| -------- | ------ | ---- | ------------------------------------------------------------ | 2271| filePath | string | 是 | 文件的应用沙箱路径。 | 2272| options | [Options](#options11) | 否 | 可选项。支持以下选项:<br/>- encoding,string类型,当数据是 string 类型时有效,表示数据的编码方式,默认 'utf-8',仅支持 'utf-8'。| 2273 2274**返回值:** 2275 2276 | 类型 | 说明 | 2277 | --------------------- | ---------- | 2278 | [ReaderIterator](#readeriterator11) | 返回文件读取迭代器。 | 2279 2280**错误码:** 2281 2282接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2283 2284**示例:** 2285 2286 ```ts 2287 import { fileIo as fs, Options } from '@kit.CoreFileKit'; 2288 let filePath = pathDir + "/test.txt"; 2289 let options: Options = { 2290 encoding: 'utf-8' 2291 }; 2292 let readerIterator = fs.readLinesSync(filePath, options); 2293 for (let it = readerIterator.next(); !it.done; it = readerIterator.next()) { 2294 console.info("content: " + it.value); 2295 } 2296 ``` 2297 2298## ReaderIterator<sup>11+</sup> 2299 2300文件读取迭代器。在调用ReaderIterator的方法前,需要先通过readLines方法(同步或异步)来构建一个ReaderIterator实例。 2301 2302### next<sup>11+</sup> 2303 2304next(): ReaderIteratorResult 2305 2306获取迭代器下一项内容。 2307 2308**系统能力**:SystemCapability.FileManagement.File.FileIO 2309 2310**返回值:** 2311 2312 | 类型 | 说明 | 2313 | --------------------- | ---------- | 2314 | [ReaderIteratorResult](#readeriteratorresult) | 文件读取迭代器返回结果。 | 2315 2316**错误码:** 2317 2318接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2319 2320> **说明**: 2321> 2322> 如果ReaderIterator读取的当前行的编码方式不是'utf-8',接口返回错误码13900037。 2323 2324**示例:** 2325 2326 ```ts 2327 import { BusinessError } from '@kit.BasicServicesKit'; 2328 import { fileIo as fs, Options } from '@kit.CoreFileKit'; 2329 let filePath = pathDir + "/test.txt"; 2330 let options: Options = { 2331 encoding: 'utf-8' 2332 }; 2333 fs.readLines(filePath, options).then((readerIterator: fs.ReaderIterator) => { 2334 for (let it = readerIterator.next(); !it.done; it = readerIterator.next()) { 2335 console.info("content: " + it.value); 2336 } 2337 }).catch((err: BusinessError) => { 2338 console.error("readLines failed with error message: " + err.message + ", error code: " + err.code); 2339 }); 2340 ``` 2341 2342## ReaderIteratorResult 2343 2344文件读取迭代器返回结果,支持ReaderIterator接口使用。 2345 2346**系统能力**:SystemCapability.FileManagement.File.FileIO 2347 2348| 名称 | 类型 | 说明 | 2349| ----------- | --------------- | ------------------ | 2350| done | boolean | 迭代器是否已完成迭代。true:已完成迭代;false:未完成迭代。 | 2351| value | string | 逐行读取的文件文本内容。 | 2352 2353## fs.readText 2354 2355readText(filePath: string, options?: ReadTextOptions): Promise<string> 2356 2357基于文本方式读取文件(即直接读取文件的文本内容),使用promise异步回调。 2358 2359**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 2360 2361**系统能力**:SystemCapability.FileManagement.File.FileIO 2362 2363**参数:** 2364 2365| 参数名 | 类型 | 必填 | 说明 | 2366| -------- | ------ | ---- | ------------------------------------------------------------ | 2367| filePath | string | 是 | 文件的应用沙箱路径。 | 2368| options | [ReadTextOptions](#readtextoptions11) | 否 | 支持如下选项:<br/>- offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读取。<br/>- length,number类型,表示期望读取数据的长度。可选,默认文件长度。<br/>- encoding,string类型,当数据是 string 类型时有效,表示数据的编码方式,默认 'utf-8',仅支持 'utf-8'。 | 2369 2370**返回值:** 2371 2372 | 类型 | 说明 | 2373 | --------------------- | ---------- | 2374 | Promise<string> | Promise对象。返回读取文件的内容。 | 2375 2376**错误码:** 2377 2378接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2379 2380**示例:** 2381 2382 ```ts 2383 import { BusinessError } from '@kit.BasicServicesKit'; 2384 let filePath = pathDir + "/test.txt"; 2385 fs.readText(filePath).then((str: string) => { 2386 console.info("readText succeed:" + str); 2387 }).catch((err: BusinessError) => { 2388 console.error("readText failed with error message: " + err.message + ", error code: " + err.code); 2389 }); 2390 ``` 2391 2392## fs.readText 2393 2394readText(filePath: string, options?: ReadTextOptions, callback: AsyncCallback<string>): void 2395 2396基于文本方式读取文件内容,使用callback异步回调。 2397 2398**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 2399 2400**系统能力**:SystemCapability.FileManagement.File.FileIO 2401 2402**参数:** 2403 2404| 参数名 | 类型 | 必填 | 说明 | 2405| -------- | --------------------------- | ---- | ------------------------------------------------------------ | 2406| filePath | string | 是 | 文件的应用沙箱路径。 | 2407| options | [ReadTextOptions](#readtextoptions11) | 否 | 支持如下选项:<br/>- offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读取。<br/>- length,number类型,表示期望读取数据的长度。可选,默认文件长度。<br/>- encoding,string类型,表示数据的编码方式,默认 'utf-8',仅支持 'utf-8'。 | 2408| callback | AsyncCallback<string> | 是 | 回调函数,返回读取文件的内容。 | 2409 2410**错误码:** 2411 2412接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2413 2414**示例:** 2415 2416 ```ts 2417 import { BusinessError } from '@kit.BasicServicesKit'; 2418 import { fileIo as fs, ReadTextOptions } from '@kit.CoreFileKit'; 2419 let filePath = pathDir + "/test.txt"; 2420 let stat = fs.statSync(filePath); 2421 let readTextOption: ReadTextOptions = { 2422 offset: 1, 2423 length: stat.size, 2424 encoding: 'utf-8' 2425 }; 2426 fs.readText(filePath, readTextOption, (err: BusinessError, str: string) => { 2427 if (err) { 2428 console.error("readText failed with error message: " + err.message + ", error code: " + err.code); 2429 } else { 2430 console.info("readText succeed:" + str); 2431 } 2432 }); 2433 ``` 2434 2435## fs.readTextSync 2436 2437readTextSync(filePath: string, options?: ReadTextOptions): string 2438 2439以同步方法基于文本方式读取文件(即直接读取文件的文本内容)。 2440 2441**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 2442 2443**系统能力**:SystemCapability.FileManagement.File.FileIO 2444 2445**参数:** 2446 2447| 参数名 | 类型 | 必填 | 说明 | 2448| -------- | ------ | ---- | ------------------------------------------------------------ | 2449| filePath | string | 是 | 文件的应用沙箱路径。 | 2450| options | [ReadTextOptions](#readtextoptions11) | 否 | 支持如下选项:<br/>- offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读取。<br/>- length,number类型,表示期望读取数据的长度。可选,默认文件长度。<br/>- encoding,string类型,当数据是 string 类型时有效,表示数据的编码方式,默认 'utf-8',仅支持 'utf-8'。 | 2451 2452**返回值:** 2453 2454 | 类型 | 说明 | 2455 | ------ | -------------------- | 2456 | string | 返回读取文件的内容。 | 2457 2458**错误码:** 2459 2460接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2461 2462**示例:** 2463 2464 ```ts 2465 import { fileIo as fs, ReadTextOptions } from '@kit.CoreFileKit'; 2466 let filePath = pathDir + "/test.txt"; 2467 let readTextOptions: ReadTextOptions = { 2468 offset: 1, 2469 length: 0, 2470 encoding: 'utf-8' 2471 }; 2472 let stat = fs.statSync(filePath); 2473 readTextOptions.length = stat.size; 2474 let str = fs.readTextSync(filePath, readTextOptions); 2475 console.info("readText succeed:" + str); 2476 ``` 2477 2478## fs.lstat 2479 2480lstat(path: string): Promise<Stat> 2481 2482获取链接文件信息,使用promise异步回调。 2483 2484**系统能力**:SystemCapability.FileManagement.File.FileIO 2485 2486**参数:** 2487 2488| 参数名 | 类型 | 必填 | 说明 | 2489| ------ | ------ | ---- | -------------------------------------- | 2490| path | string | 是 | 文件的应用沙箱路径。 | 2491 2492**返回值:** 2493 2494 | 类型 | 说明 | 2495 | ---------------------------- | ---------- | 2496 | Promise<[Stat](#stat)> | Promise对象。返回Stat对象,表示文件的具体信息,详情见Stat。 | 2497 2498**错误码:** 2499 2500接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2501 2502**示例:** 2503 2504 ```ts 2505 import { BusinessError } from '@kit.BasicServicesKit'; 2506 let filePath = pathDir + "/linkToFile"; 2507 fs.lstat(filePath).then((stat: fs.Stat) => { 2508 console.info("lstat succeed, the size of file is " + stat.size); 2509 }).catch((err: BusinessError) => { 2510 console.error("lstat failed with error message: " + err.message + ", error code: " + err.code); 2511 }); 2512 ``` 2513 2514## fs.lstat 2515 2516lstat(path: string, callback: AsyncCallback<Stat>): void 2517 2518获取链接文件信息,使用callback异步回调。 2519 2520**系统能力**:SystemCapability.FileManagement.File.FileIO 2521 2522**参数:** 2523 2524| 参数名 | 类型 | 必填 | 说明 | 2525| -------- | ---------------------------------- | ---- | -------------------------------------- | 2526| path | string | 是 | 文件的应用沙箱路径。 | 2527| callback | AsyncCallback<[Stat](#stat)> | 是 | 异步获取文件具体信息之后的回调。 | 2528 2529**错误码:** 2530 2531接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2532 2533**示例:** 2534 2535 ```ts 2536 import { BusinessError } from '@kit.BasicServicesKit'; 2537 let filePath = pathDir + "/linkToFile"; 2538 fs.lstat(filePath, (err: BusinessError, stat: fs.Stat) => { 2539 if (err) { 2540 console.error("lstat failed with error message: " + err.message + ", error code: " + err.code); 2541 } else { 2542 console.info("lstat succeed, the size of file is " + stat.size); 2543 } 2544 }); 2545 ``` 2546 2547## fs.lstatSync 2548 2549lstatSync(path: string): Stat 2550 2551以同步方法获取链接文件信息。 2552 2553**系统能力**:SystemCapability.FileManagement.File.FileIO 2554 2555**参数:** 2556 2557| 参数名 | 类型 | 必填 | 说明 | 2558| ------ | ------ | ---- | -------------------------------------- | 2559| path | string | 是 | 文件的应用沙箱路径。 | 2560 2561**返回值:** 2562 2563 | 类型 | 说明 | 2564 | ------------- | ---------- | 2565 | [Stat](#stat) | 表示文件的具体信息。 | 2566 2567**错误码:** 2568 2569接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2570 2571**示例:** 2572 2573 ```ts 2574 let filePath = pathDir + "/linkToFile"; 2575 let fileStat = fs.lstatSync(filePath); 2576 console.info("lstat succeed, the size of file is " + fileStat.size); 2577 ``` 2578 2579## fs.rename 2580 2581rename(oldPath: string, newPath: string): Promise<void> 2582 2583重命名文件或目录,使用promise异步回调。 2584 2585> **说明:** 2586> 2587> 该接口不支持在分布式文件路径下操作。 2588 2589**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 2590 2591**系统能力**:SystemCapability.FileManagement.File.FileIO 2592 2593**参数:** 2594 2595| 参数名 | 类型 | 必填 | 说明 | 2596| ------- | ------ | ---- | ---------------------------- | 2597| oldPath | string | 是 | 文件的应用沙箱原路径。 | 2598| newPath | string | 是 | 文件的应用沙箱新路径。 | 2599 2600**返回值:** 2601 2602 | 类型 | 说明 | 2603 | ------------------- | ---------------------------- | 2604 | Promise<void> | Promise对象。无返回值。 | 2605 2606**错误码:** 2607 2608接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2609 2610**示例:** 2611 2612 ```ts 2613 import { BusinessError } from '@kit.BasicServicesKit'; 2614 let srcFile = pathDir + "/test.txt"; 2615 let dstFile = pathDir + "/new.txt"; 2616 fs.rename(srcFile, dstFile).then(() => { 2617 console.info("rename succeed"); 2618 }).catch((err: BusinessError) => { 2619 console.error("rename failed with error message: " + err.message + ", error code: " + err.code); 2620 }); 2621 ``` 2622 2623## fs.rename 2624 2625rename(oldPath: string, newPath: string, callback: AsyncCallback<void>): void 2626 2627重命名文件或目录,使用callback异步回调。 2628 2629> **说明:** 2630> 2631> 该接口不支持在分布式文件路径下操作。 2632 2633**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 2634 2635**系统能力**:SystemCapability.FileManagement.File.FileIO 2636 2637**参数:** 2638 2639| 参数名 | 类型 | 必填 | 说明 | 2640| -------- | ------------------------- | ---- | ---------------------------- | 2641| oldPath | string | 是 | 文件的应用沙箱原路径。 | 2642| newPath | string | 是 | 文件的应用沙箱新路径。 | 2643| callback | AsyncCallback<void> | 是 | 异步重命名文件之后的回调。 | 2644 2645**错误码:** 2646 2647接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2648 2649**示例:** 2650 2651 ```ts 2652 import { BusinessError } from '@kit.BasicServicesKit'; 2653 let srcFile = pathDir + "/test.txt"; 2654 let dstFile = pathDir + "/new.txt"; 2655 fs.rename(srcFile, dstFile, (err: BusinessError) => { 2656 if (err) { 2657 console.error("rename failed with error message: " + err.message + ", error code: " + err.code); 2658 } else { 2659 console.info("rename succeed"); 2660 } 2661 }); 2662 ``` 2663 2664## fs.renameSync 2665 2666renameSync(oldPath: string, newPath: string): void 2667 2668以同步方法重命名文件或目录。 2669 2670> **说明:** 2671> 2672> 该接口不支持在分布式文件路径下操作。 2673 2674**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 2675 2676**系统能力**:SystemCapability.FileManagement.File.FileIO 2677 2678**参数:** 2679 2680| 参数名 | 类型 | 必填 | 说明 | 2681| ------- | ------ | ---- | ---------------------------- | 2682| oldPath | string | 是 | 文件的应用沙箱原路径。 | 2683| newPath | string | 是 | 文件的应用沙箱新路径。 | 2684 2685**错误码:** 2686 2687接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2688 2689**示例:** 2690 2691 ```ts 2692 let srcFile = pathDir + "/test.txt"; 2693 let dstFile = pathDir + "/new.txt"; 2694 fs.renameSync(srcFile, dstFile); 2695 ``` 2696 2697## fs.fsync 2698 2699fsync(fd: number): Promise<void> 2700 2701将文件系统缓存数据写入磁盘,使用promise异步回调。 2702 2703**系统能力**:SystemCapability.FileManagement.File.FileIO 2704 2705**参数:** 2706 2707 | 参数名 | 类型 | 必填 | 说明 | 2708 | ---- | ------ | ---- | ------------ | 2709 | fd | number | 是 | 已打开的文件描述符。 | 2710 2711**返回值:** 2712 2713 | 类型 | 说明 | 2714 | ------------------- | ---------------------------- | 2715 | Promise<void> | Promise对象。无返回值。 | 2716 2717**错误码:** 2718 2719接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2720 2721**示例:** 2722 2723 ```ts 2724 import { BusinessError } from '@kit.BasicServicesKit'; 2725 let filePath = pathDir + "/test.txt"; 2726 let file = fs.openSync(filePath); 2727 fs.fsync(file.fd).then(() => { 2728 console.info("sync data succeed"); 2729 }).catch((err: BusinessError) => { 2730 console.error("sync data failed with error message: " + err.message + ", error code: " + err.code); 2731 }).finally(() => { 2732 fs.closeSync(file); 2733 }); 2734 ``` 2735 2736## fs.fsync 2737 2738fsync(fd: number, callback: AsyncCallback<void>): void 2739 2740将文件系统缓存数据写入磁盘,使用callback异步回调。 2741 2742**系统能力**:SystemCapability.FileManagement.File.FileIO 2743 2744**参数:** 2745 2746 | 参数名 | 类型 | 必填 | 说明 | 2747 | -------- | ------------------------- | ---- | --------------- | 2748 | fd | number | 是 | 已打开的文件描述符。 | 2749 | callback | AsyncCallback<void> | 是 | 异步将文件数据同步之后的回调。 | 2750 2751**错误码:** 2752 2753接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2754 2755**示例:** 2756 2757 ```ts 2758 import { BusinessError } from '@kit.BasicServicesKit'; 2759 let filePath = pathDir + "/test.txt"; 2760 let file = fs.openSync(filePath); 2761 fs.fsync(file.fd, (err: BusinessError) => { 2762 if (err) { 2763 console.error("fsync failed with error message: " + err.message + ", error code: " + err.code); 2764 } else { 2765 console.info("fsync succeed"); 2766 } 2767 fs.closeSync(file); 2768 }); 2769 ``` 2770 2771 2772## fs.fsyncSync 2773 2774fsyncSync(fd: number): void 2775 2776以同步方法将文件系统缓存数据写入磁盘。 2777 2778**系统能力**:SystemCapability.FileManagement.File.FileIO 2779 2780**参数:** 2781 2782 | 参数名 | 类型 | 必填 | 说明 | 2783 | ---- | ------ | ---- | ------------ | 2784 | fd | number | 是 | 已打开的文件描述符。 | 2785 2786**错误码:** 2787 2788接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2789 2790**示例:** 2791 2792 ```ts 2793 let filePath = pathDir + "/test.txt"; 2794 let file = fs.openSync(filePath); 2795 fs.fsyncSync(file.fd); 2796 fs.closeSync(file); 2797 ``` 2798 2799## fs.fdatasync 2800 2801fdatasync(fd: number): Promise<void> 2802 2803实现文件内容数据同步,使用promise异步回调。 2804 2805**系统能力**:SystemCapability.FileManagement.File.FileIO 2806 2807**参数:** 2808 2809 | 参数名 | 类型 | 必填 | 说明 | 2810 | ---- | ------ | ---- | ------------ | 2811 | fd | number | 是 | 已打开的文件描述符。 | 2812 2813**返回值:** 2814 2815 | 类型 | 说明 | 2816 | ------------------- | ---------------------------- | 2817 | Promise<void> | Promise对象。无返回值。 | 2818 2819**错误码:** 2820 2821接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2822 2823**示例:** 2824 2825 ```ts 2826 import { BusinessError } from '@kit.BasicServicesKit'; 2827 let filePath = pathDir + "/test.txt"; 2828 let file = fs.openSync(filePath); 2829 fs.fdatasync(file.fd).then(() => { 2830 console.info("sync data succeed"); 2831 }).catch((err: BusinessError) => { 2832 console.error("sync data failed with error message: " + err.message + ", error code: " + err.code); 2833 }).finally(() => { 2834 fs.closeSync(file); 2835 }); 2836 ``` 2837 2838## fs.fdatasync 2839 2840fdatasync(fd: number, callback: AsyncCallback<void>): void 2841 2842实现文件内容数据同步,使用callback异步回调。 2843 2844**系统能力**:SystemCapability.FileManagement.File.FileIO 2845 2846**参数:** 2847 2848 | 参数名 | 类型 | 必填 | 说明 | 2849 | -------- | ------------------------------- | ---- | ----------------- | 2850 | fd | number | 是 | 已打开的文件描述符。 | 2851 | callback | AsyncCallback<void> | 是 | 异步将文件内容数据同步之后的回调。 | 2852 2853**错误码:** 2854 2855接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2856 2857**示例:** 2858 2859 ```ts 2860 import { BusinessError } from '@kit.BasicServicesKit'; 2861 let filePath = pathDir + "/test.txt"; 2862 let file = fs.openSync(filePath); 2863 fs.fdatasync(file.fd, (err: BusinessError) => { 2864 if (err) { 2865 console.error("fdatasync failed with error message: " + err.message + ", error code: " + err.code); 2866 } else { 2867 console.info("fdatasync succeed"); 2868 } 2869 fs.closeSync(file); 2870 }); 2871 ``` 2872 2873## fs.fdatasyncSync 2874 2875fdatasyncSync(fd: number): void 2876 2877以同步方法实现文件内容的数据同步。 2878 2879**系统能力**:SystemCapability.FileManagement.File.FileIO 2880 2881**参数:** 2882 2883 | 参数名 | 类型 | 必填 | 说明 | 2884 | ---- | ------ | ---- | ------------ | 2885 | fd | number | 是 | 已打开的文件描述符。 | 2886 2887**错误码:** 2888 2889接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2890 2891**示例:** 2892 2893 ```ts 2894 let filePath = pathDir + "/test.txt"; 2895 let file = fs.openSync(filePath); 2896 fs.fdatasyncSync(file.fd); 2897 fs.closeSync(file); 2898 ``` 2899 2900## fs.symlink 2901 2902symlink(target: string, srcPath: string): Promise<void> 2903 2904基于文件路径创建符号链接,使用promise异步回调。 2905 2906**系统能力**:SystemCapability.FileManagement.File.FileIO 2907 2908**参数:** 2909 2910| 参数名 | 类型 | 必填 | 说明 | 2911| ------- | ------ | ---- | ---------------------------- | 2912| target | string | 是 | 要链接的目标文件的应用沙箱路径。 | 2913| srcPath | string | 是 | 符号链接文件的应用沙箱路径。 | 2914 2915**返回值:** 2916 2917 | 类型 | 说明 | 2918 | ------------------- | ---------------------------- | 2919 | Promise<void> | Promise对象。无返回值。 | 2920 2921**错误码:** 2922 2923接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2924 2925**示例:** 2926 2927 ```ts 2928 import { BusinessError } from '@kit.BasicServicesKit'; 2929 let srcFile = pathDir + "/test.txt"; 2930 let dstFile = pathDir + "/test"; 2931 fs.symlink(srcFile, dstFile).then(() => { 2932 console.info("symlink succeed"); 2933 }).catch((err: BusinessError) => { 2934 console.error("symlink failed with error message: " + err.message + ", error code: " + err.code); 2935 }); 2936 ``` 2937 2938 2939## fs.symlink 2940symlink(target: string, srcPath: string, callback: AsyncCallback<void>): void 2941 2942基于文件路径创建符号链接,使用callback异步回调。 2943 2944**系统能力**:SystemCapability.FileManagement.File.FileIO 2945 2946**参数:** 2947 2948| 参数名 | 类型 | 必填 | 说明 | 2949| -------- | ------------------------- | ---- | -------------------------------- | 2950| target | string | 是 | 要链接的目标文件的应用沙箱路径。 | 2951| srcPath | string | 是 | 符号链接文件的应用沙箱路径。 | 2952| callback | AsyncCallback<void> | 是 | 异步创建符号链接信息之后的回调。 | 2953 2954**错误码:** 2955 2956接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2957 2958**示例:** 2959 2960 ```ts 2961 import { BusinessError } from '@kit.BasicServicesKit'; 2962 let srcFile = pathDir + "/test.txt"; 2963 let dstFile = pathDir + "/test"; 2964 fs.symlink(srcFile, dstFile, (err: BusinessError) => { 2965 if (err) { 2966 console.error("symlink failed with error message: " + err.message + ", error code: " + err.code); 2967 } else { 2968 console.info("symlink succeed"); 2969 } 2970 }); 2971 ``` 2972 2973## fs.symlinkSync 2974 2975symlinkSync(target: string, srcPath: string): void 2976 2977以同步的方法基于文件路径创建符号链接。 2978 2979**系统能力**:SystemCapability.FileManagement.File.FileIO 2980 2981**参数:** 2982 2983| 参数名 | 类型 | 必填 | 说明 | 2984| ------- | ------ | ---- | ---------------------------- | 2985| target | string | 是 | 要链接的目标文件的应用沙箱路径。 | 2986| srcPath | string | 是 | 符号链接文件的应用沙箱路径。 | 2987 2988**错误码:** 2989 2990接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2991 2992**示例:** 2993 2994 ```ts 2995 let srcFile = pathDir + "/test.txt"; 2996 let dstFile = pathDir + "/test"; 2997 fs.symlinkSync(srcFile, dstFile); 2998 ``` 2999 3000## fs.listFile 3001listFile(path: string, options?: ListFileOptions): Promise<string[]> 3002 3003默认列出当前目录下所有文件名和目录名。支持过滤。使用promise异步回调。 3004 3005可通过配置options中recursion参数实现递归列出所有文件的相对路径,相对路径以“/”开头。 3006 3007**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 3008 3009**系统能力**:SystemCapability.FileManagement.File.FileIO 3010 3011**参数:** 3012 3013 | 参数名 | 类型 | 必填 | 说明 | 3014 | ------ | ------ | ---- | --------------------------- | 3015 | path | string | 是 | 目录的应用沙箱路径。 | 3016 | options | [ListFileOptions](#listfileoptions11) | 否 | 文件过滤选项。默认不进行过滤。 | 3017 3018 3019**返回值:** 3020 3021 | 类型 | 说明 | 3022 | --------------------- | ---------- | 3023 | Promise<string[]> | Promise对象。返回文件名数组。 | 3024 3025**错误码:** 3026 3027接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3028 3029**示例:** 3030 3031 ```ts 3032 import { BusinessError } from '@kit.BasicServicesKit'; 3033 import { fileIo as fs, Filter, ListFileOptions } from '@kit.CoreFileKit'; 3034 let listFileOption: ListFileOptions = { 3035 recursion: false, 3036 listNum: 0, 3037 filter: { 3038 suffix: [".png", ".jpg", ".jpeg"], 3039 displayName: ["*abc", "efg*"], 3040 fileSizeOver: 1024 3041 } 3042 } 3043 fs.listFile(pathDir, listFileOption).then((filenames: Array<string>) => { 3044 console.info("listFile succeed"); 3045 for (let i = 0; i < filenames.length; i++) { 3046 console.info("fileName: %s", filenames[i]); 3047 } 3048 }).catch((err: BusinessError) => { 3049 console.error("list file failed with error message: " + err.message + ", error code: " + err.code); 3050 }); 3051 ``` 3052 3053## fs.listFile 3054listFile(path: string, options?: ListFileOptions, callback: AsyncCallback<string[]>): void 3055 3056默认列出当前目录下所有文件名和目录名。支持过滤。使用callback异步回调。 3057 3058可通过配置options中recursion参数实现递归列出所有文件的相对路径,相对路径以“/”开头。 3059 3060**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 3061 3062**系统能力**:SystemCapability.FileManagement.File.FileIO 3063 3064**参数:** 3065 3066 | 参数名 | 类型 | 必填 | 说明 | 3067 | ------ | ------ | ---- | --------------------------- | 3068 | path | string | 是 | 目录的应用沙箱路径。 | 3069 | options | [ListFileOptions](#listfileoptions11) | 否 | 文件过滤选项。默认不进行过滤。 | 3070 | callback | AsyncCallback<string[]> | 是 | 异步列出文件名数组之后的回调。 | 3071 3072 3073**错误码:** 3074 3075接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3076 3077**示例:** 3078 3079 ```ts 3080 import { BusinessError } from '@kit.BasicServicesKit'; 3081 import { fileIo as fs, Filter, ListFileOptions } from '@kit.CoreFileKit'; 3082 let listFileOption: ListFileOptions = { 3083 recursion: false, 3084 listNum: 0, 3085 filter: { 3086 suffix: [".png", ".jpg", ".jpeg"], 3087 displayName: ["*abc", "efg*"], 3088 fileSizeOver: 1024 3089 } 3090 }; 3091 fs.listFile(pathDir, listFileOption, (err: BusinessError, filenames: Array<string>) => { 3092 if (err) { 3093 console.error("list file failed with error message: " + err.message + ", error code: " + err.code); 3094 } else { 3095 console.info("listFile succeed"); 3096 for (let i = 0; i < filenames.length; i++) { 3097 console.info("filename: %s", filenames[i]); 3098 } 3099 } 3100 }); 3101 ``` 3102 3103## fs.listFileSync 3104 3105listFileSync(path: string, options?: ListFileOptions): string[] 3106 3107默认以同步方式列出当前目录下所有文件名和目录名。支持过滤。 3108 3109可通过配置options中recursion参数实现递归列出所有文件的相对路径,相对路径以“/”开头。 3110 3111**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 3112 3113**系统能力**:SystemCapability.FileManagement.File.FileIO 3114 3115**参数:** 3116 3117 | 参数名 | 类型 | 必填 | 说明 | 3118 | ------ | ------ | ---- | --------------------------- | 3119 | path | string | 是 | 目录的应用沙箱路径。 | 3120 | options | [ListFileOptions](#listfileoptions11) | 否 | 文件过滤选项。默认不进行过滤。 | 3121 3122 3123**返回值:** 3124 3125 | 类型 | 说明 | 3126 | --------------------- | ---------- | 3127 | string[] | 返回文件名数组。 | 3128 3129**错误码:** 3130 3131接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3132 3133**示例:** 3134 3135 ```ts 3136 import { fileIo as fs, Filter, ListFileOptions} from '@kit.CoreFileKit'; 3137 let listFileOption: ListFileOptions = { 3138 recursion: false, 3139 listNum: 0, 3140 filter: { 3141 suffix: [".png", ".jpg", ".jpeg"], 3142 displayName: ["*abc", "efg*"], 3143 fileSizeOver: 1024 3144 } 3145 }; 3146 let filenames = fs.listFileSync(pathDir, listFileOption); 3147 console.info("listFile succeed"); 3148 for (let i = 0; i < filenames.length; i++) { 3149 console.info("filename: %s", filenames[i]); 3150 } 3151 ``` 3152 3153## fs.lseek<sup>11+</sup> 3154 3155lseek(fd: number, offset: number, whence?: WhenceType): number 3156 3157调整文件偏移指针位置。 3158 3159**系统能力**:SystemCapability.FileManagement.File.FileIO 3160 3161**参数:** 3162 3163 | 参数名 | 类型 | 必填 | 说明 | 3164 | ------ | ------ | ---- | --------------------------- | 3165 | fd | number | 是 | 文件描述符。 | 3166 | offset | number | 是 | 相对偏移位置,单位为字节。 | 3167 | whence | [WhenceType](#whencetype11) | 否 | 偏移指针相对位置类型。不指定则默认为文件起始位置处。| 3168 3169**返回值:** 3170 3171 | 类型 | 说明 | 3172 | --------------------- | ---------- | 3173 | number | 当前文件偏移指针位置(相对于文件头的偏移量,单位为字节)。 | 3174 3175**错误码:** 3176 3177接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3178 3179**示例:** 3180 3181 ```ts 3182 let filePath = pathDir + "/test.txt"; 3183 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 3184 console.info('The current offset is at ' + fs.lseek(file.fd, 5, fs.WhenceType.SEEK_SET)); 3185 fs.closeSync(file); 3186 ``` 3187 3188## fs.moveDir<sup>10+</sup> 3189 3190moveDir(src: string, dest: string, mode?: number): Promise\<void> 3191 3192移动源目录至目标路径下,使用promise异步回调。 3193 3194> **说明:** 3195> 3196> 该接口不支持在分布式文件路径下操作。 3197 3198**系统能力**:SystemCapability.FileManagement.File.FileIO 3199 3200**参数:** 3201 3202 | 参数名 | 类型 | 必填 | 说明 | 3203 | ------ | ------ | ---- | --------------------------- | 3204 | src | string | 是 | 源目录的应用沙箱路径。 | 3205 | dest | string | 是 | 目标目录的应用沙箱路径。 | 3206 | mode | number | 否 | 移动模式,默认值为0。<br/>- mode为0,目录级别抛异常。若目标目录下存在与源目录名冲突的非空目录,则抛出异常。<br/>- mode为1,文件级别抛异常。目标目录下存在与源目录名冲突的目录,若冲突目录下存在同名文件,则抛出异常。源目录下未冲突的文件全部移动至目标目录下,目标目录下未冲突文件将继续保留,且冲突文件信息将在抛出异常的data属性中以Array\<[ConflictFiles](#conflictfiles10)>形式提供。<br/>- mode为2,文件级别强制覆盖。目标目录下存在与源目录名冲突的目录,若冲突目录下存在同名文件,则强制覆盖冲突目录下所有同名文件,未冲突文件将继续保留。<br/>- mode为3,目录级别强制覆盖。移动源目录至目标目录下,目标目录下移动的目录内容与源目录完全一致。若目标目录下存在与源目录名冲突的目录,该目录下的所有原始文件将被删除。| 3207 3208**返回值:** 3209 3210 | 类型 | 说明 | 3211 | ------------------- | ---------------------------- | 3212 | Promise<void> | Promise对象。无返回值。 | 3213 3214**错误码:** 3215 3216接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3217 3218**示例:** 3219 3220 ```ts 3221 import { BusinessError } from '@kit.BasicServicesKit'; 3222 let srcPath = pathDir + "/srcDir"; 3223 let destPath = pathDir + "/destDir"; 3224 fs.moveDir(srcPath, destPath, 1).then(() => { 3225 console.info("move directory succeed"); 3226 }).catch((err: BusinessError) => { 3227 console.error("move directory failed with error message: " + err.message + ", error code: " + err.code); 3228 }); 3229 ``` 3230 3231## fs.moveDir<sup>10+</sup> 3232 3233moveDir(src: string, dest: string, mode: number, callback: AsyncCallback\<void, Array\<ConflictFiles>>): void 3234 3235移动源目录至目标路径下,支持设置移动模式。使用callback异步回调。 3236 3237> **说明:** 3238> 3239> 该接口不支持在分布式文件路径下操作。 3240 3241**系统能力**:SystemCapability.FileManagement.File.FileIO 3242 3243**参数:** 3244 3245 | 参数名 | 类型 | 必填 | 说明 | 3246 | ------ | ------ | ---- | --------------------------- | 3247 | src | string | 是 | 源目录的应用沙箱路径。 | 3248 | dest | string | 是 | 目标目录的应用沙箱路径。 | 3249 | mode | number | 是 | 移动模式,默认值为0。<br/>- mode为0,目录级别抛异常。若目标目录下存在与源目录名冲突的目录,则抛出异常。<br/>- mode为1,文件级别抛异常。目标目录下存在与源目录名冲突的目录,若冲突目录下存在同名文件,则抛出异常。源目录下未冲突的文件全部移动至目标目录下,目标目录下未冲突文件将继续保留,且冲突文件信息将在抛出异常的data属性中以Array\<[ConflictFiles](#conflictfiles10)>形式提供。<br/>- mode为2,文件级别强制覆盖。目标目录下存在与源目录名冲突的目录,若冲突目录下存在同名文件,则强制覆盖冲突目录下所有同名文件,未冲突文件将继续保留。<br/>- mode为3,目录级别强制覆盖。移动源目录至目标目录下,目标目录下移动的目录内容与源目录完全一致。若目标目录下存在与源目录名冲突的目录,该目录下所有原始文件将被删除。| 3250 | callback | AsyncCallback<void, Array<[ConflictFiles](#conflictfiles10)>> | 是 | 异步移动目录之后的回调。 | 3251 3252**错误码:** 3253 3254接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3255 3256**示例:** 3257 3258 ```ts 3259 import { BusinessError } from '@kit.BasicServicesKit'; 3260 import { fileIo as fs, ConflictFiles } from '@kit.CoreFileKit'; 3261 let srcPath = pathDir + "/srcDir"; 3262 let destPath = pathDir + "/destDir"; 3263 fs.moveDir(srcPath, destPath, 1, (err: BusinessError<Array<ConflictFiles>>) => { 3264 if (err && err.code == 13900015 && err.data?.length !== undefined) { 3265 for (let i = 0; i < err.data.length; i++) { 3266 console.error("move directory failed with conflicting files: " + err.data[i].srcFile + " " + err.data[i].destFile); 3267 } 3268 } else if (err) { 3269 console.error("move directory failed with error message: " + err.message + ", error code: " + err.code); 3270 } else { 3271 console.info("move directory succeed"); 3272 } 3273 }); 3274 ``` 3275 3276 ## fs.moveDir<sup>10+</sup> 3277 3278moveDir(src: string, dest: string, callback: AsyncCallback\<void, Array\<ConflictFiles>>): void 3279 3280移动源目录至目标路径下。使用callback异步回调。 3281 3282移动模式为目录级别抛异常。当目标目录下存在与源目录名冲突的目录,则抛出异常。 3283 3284> **说明:** 3285> 3286> 该接口不支持在分布式文件路径下操作。 3287 3288**系统能力**:SystemCapability.FileManagement.File.FileIO 3289 3290**参数:** 3291 3292 | 参数名 | 类型 | 必填 | 说明 | 3293 | ------ | ------ | ---- | --------------------------- | 3294 | src | string | 是 | 源目录的应用沙箱路径。 | 3295 | dest | string | 是 | 目标目录的应用沙箱路径。 | 3296 | callback | AsyncCallback<void, Array<[ConflictFiles](#conflictfiles10)>> | 是 | 异步移动目录之后的回调。 | 3297 3298**错误码:** 3299 3300接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3301 3302**示例:** 3303 3304 ```ts 3305 import { BusinessError } from '@kit.BasicServicesKit'; 3306 import { fileIo as fs, ConflictFiles } from '@kit.CoreFileKit'; 3307 let srcPath = pathDir + "/srcDir"; 3308 let destPath = pathDir + "/destDir"; 3309 fs.moveDir(srcPath, destPath, (err: BusinessError<Array<ConflictFiles>>) => { 3310 if (err && err.code == 13900015 && err.data?.length !== undefined) { 3311 for (let i = 0; i < err.data.length; i++) { 3312 console.error("move directory failed with conflicting files: " + err.data[i].srcFile + " " + err.data[i].destFile); 3313 } 3314 } else if (err) { 3315 console.error("move directory failed with error message: " + err.message + ", error code: " + err.code); 3316 } else { 3317 console.info("move directory succeed"); 3318 } 3319 }); 3320 ``` 3321 3322## fs.moveDirSync<sup>10+</sup> 3323 3324moveDirSync(src: string, dest: string, mode?: number): void 3325 3326以同步方法移动源目录至目标路径下。 3327 3328> **说明:** 3329> 3330> 该接口不支持在分布式文件路径下操作。 3331 3332**系统能力**:SystemCapability.FileManagement.File.FileIO 3333 3334**参数:** 3335 3336 | 参数名 | 类型 | 必填 | 说明 | 3337 | ------ | ------ | ---- | --------------------------- | 3338 | src | string | 是 | 源目录的应用沙箱路径。 | 3339 | dest | string | 是 | 目标目录的应用沙箱路径。 | 3340 | mode | number | 否 | 移动模式,默认值为0。<br/>- mode为0,目录级别抛异常。若目标目录下存在与源目录名冲突的目录,则抛出异常。<br/>- mode为1,文件级别抛异常。目标目录下存在与源目录名冲突的目录,若冲突目录下存在同名文件,则抛出异常。源目录下未冲突的文件全部移动至目标目录下,目标目录下未冲突文件将继续保留,且冲突文件信息将在抛出异常的data属性中以Array\<[ConflictFiles](#conflictfiles10)>形式提供。<br/>- mode为2,文件级别强制覆盖。目标目录下存在与源目录名冲突的目录,若冲突目录下存在同名文件,则强制覆盖冲突目录下所有同名文件,未冲突文件将继续保留。<br/>- mode为3,目录级别强制覆盖。移动源目录至目标目录下,目标目录下移动的目录内容与源目录完全一致。若目标目录下存在与源目录名冲突的目录,该目录下所有原始文件将被删除。| 3341 3342**错误码:** 3343 3344接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3345 3346**示例:** 3347 3348```ts 3349import { BusinessError } from '@kit.BasicServicesKit'; 3350import { fileIo as fs, ConflictFiles } from '@kit.CoreFileKit'; 3351let srcPath = pathDir + "/srcDir"; 3352let destPath = pathDir + "/destDir"; 3353try { 3354 fs.moveDirSync(srcPath, destPath, 1); 3355 console.info("move directory succeed"); 3356} catch (error) { 3357 let err: BusinessError<Array<ConflictFiles>> = error as BusinessError<Array<ConflictFiles>>; 3358 if (err.code == 13900015 && err.data?.length !== undefined) { 3359 for (let i = 0; i < err.data.length; i++) { 3360 console.error("move directory failed with conflicting files: " + err.data[i].srcFile + " " + err.data[i].destFile); 3361 } 3362 } else { 3363 console.error("move directory failed with error message: " + err.message + ", error code: " + err.code); 3364 } 3365} 3366``` 3367 3368## fs.moveFile 3369 3370moveFile(src: string, dest: string, mode?: number): Promise\<void> 3371 3372移动文件,使用promise异步回调。 3373 3374> **说明:** 3375> 3376> 该接口不支持在分布式文件路径下操作。 3377 3378**系统能力**:SystemCapability.FileManagement.File.FileIO 3379 3380**参数:** 3381 3382 | 参数名 | 类型 | 必填 | 说明 | 3383 | ------ | ------ | ---- | --------------------------- | 3384 | src | string | 是 | 源文件的应用沙箱路径。 | 3385 | dest | string | 是 | 目标文件的应用沙箱路径。 | 3386 | mode | number | 否 | 移动模式。若mode为0,移动位置存在同名文件时,强制移动覆盖。若mode为1,移动位置存在同名文件时,抛出异常。默认为0。 | 3387 3388**返回值:** 3389 3390 | 类型 | 说明 | 3391 | ------------------- | ---------------------------- | 3392 | Promise<void> | Promise对象。无返回值。 | 3393 3394**错误码:** 3395 3396接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3397 3398**示例:** 3399 3400 ```ts 3401 import { BusinessError } from '@kit.BasicServicesKit'; 3402 let srcPath = pathDir + "/source.txt"; 3403 let destPath = pathDir + "/dest.txt"; 3404 fs.moveFile(srcPath, destPath, 0).then(() => { 3405 console.info("move file succeed"); 3406 }).catch((err: BusinessError) => { 3407 console.error("move file failed with error message: " + err.message + ", error code: " + err.code); 3408 }); 3409 ``` 3410 3411## fs.moveFile 3412 3413moveFile(src: string, dest: string, mode: number, callback: AsyncCallback\<void>): void 3414 3415移动文件,支持设置移动模式。使用callback异步回调。 3416 3417> **说明:** 3418> 3419> 该接口不支持在分布式文件路径下操作。 3420 3421**系统能力**:SystemCapability.FileManagement.File.FileIO 3422 3423**参数:** 3424 3425 | 参数名 | 类型 | 必填 | 说明 | 3426 | ------ | ------ | ---- | --------------------------- | 3427 | src | string | 是 | 源文件的应用沙箱路径。 | 3428 | dest | string | 是 | 目标文件的应用沙箱路径。 | 3429 | mode | number | 是 | 移动模式。若mode为0,移动位置存在同名文件时,强制移动覆盖。若mode为1,移动位置存在同名文件时,抛出异常。默认为0。 | 3430 | callback | AsyncCallback<void> | 是 | 异步移动文件之后的回调。 | 3431 3432**错误码:** 3433 3434接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3435 3436**示例:** 3437 3438 ```ts 3439 import { BusinessError } from '@kit.BasicServicesKit'; 3440 let srcPath = pathDir + "/source.txt"; 3441 let destPath = pathDir + "/dest.txt"; 3442 fs.moveFile(srcPath, destPath, 0, (err: BusinessError) => { 3443 if (err) { 3444 console.error("move file failed with error message: " + err.message + ", error code: " + err.code); 3445 } else { 3446 console.info("move file succeed"); 3447 } 3448 }); 3449 ``` 3450 3451## fs.moveFile 3452 3453moveFile(src: string, dest: string, callback: AsyncCallback\<void>): void 3454 3455移动文件。如果移动位置存在同名文件,将强制覆盖。使用callback异步回调。 3456 3457> **说明:** 3458> 3459> 该接口不支持在分布式文件路径下操作。 3460 3461**系统能力**:SystemCapability.FileManagement.File.FileIO 3462 3463**参数:** 3464 3465 | 参数名 | 类型 | 必填 | 说明 | 3466 | ------ | ------ | ---- | --------------------------- | 3467 | src | string | 是 | 源文件的应用沙箱路径。 | 3468 | dest | string | 是 | 目标文件的应用沙箱路径。 | 3469 | callback | AsyncCallback<void> | 是 | 异步移动文件之后的回调。 | 3470 3471**错误码:** 3472 3473接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3474 3475**示例:** 3476 3477 ```ts 3478 import { BusinessError } from '@kit.BasicServicesKit'; 3479 let srcPath = pathDir + "/source.txt"; 3480 let destPath = pathDir + "/dest.txt"; 3481 fs.moveFile(srcPath, destPath, (err: BusinessError) => { 3482 if (err) { 3483 console.error("move file failed with error message: " + err.message + ", error code: " + err.code); 3484 } else { 3485 console.info("move file succeed"); 3486 } 3487 }); 3488 ``` 3489 3490## fs.moveFileSync 3491 3492moveFileSync(src: string, dest: string, mode?: number): void 3493 3494以同步方式移动文件。 3495 3496> **说明:** 3497> 3498> 该接口不支持在分布式文件路径下操作。 3499 3500**系统能力**:SystemCapability.FileManagement.File.FileIO 3501 3502**参数:** 3503 3504 | 参数名 | 类型 | 必填 | 说明 | 3505 | ------ | ------ | ---- | --------------------------- | 3506 | src | string | 是 | 源文件的应用沙箱路径。 | 3507 | dest | string | 是 | 目标文件的应用沙箱路径。 | 3508 | mode | number | 否 | 移动模式。若mode为0,移动位置存在同名文件时,强制移动覆盖。若mode为1,移动位置存在同名文件时,抛出异常。默认为0。 | 3509 3510**错误码:** 3511 3512接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3513 3514**示例:** 3515 3516 ```ts 3517 let srcPath = pathDir + "/source.txt"; 3518 let destPath = pathDir + "/dest.txt"; 3519 fs.moveFileSync(srcPath, destPath, 0); 3520 console.info("move file succeed"); 3521 ``` 3522 3523## fs.mkdtemp 3524 3525mkdtemp(prefix: string): Promise<string> 3526 3527创建临时目录,使用promise异步回调。 3528 3529**系统能力**:SystemCapability.FileManagement.File.FileIO 3530 3531**参数:** 3532 3533 | 参数名 | 类型 | 必填 | 说明 | 3534 | ------ | ------ | ---- | --------------------------- | 3535 | prefix | string | 是 | 指定目录路径,命名时需要以"XXXXXX"作为结尾。路径末尾的"XXXXXX"字符串将被替换为随机字符,以创建唯一的目录名。 | 3536 3537**返回值:** 3538 3539 | 类型 | 说明 | 3540 | --------------------- | ---------- | 3541 | Promise<string> | Promise对象。返回生成的唯一目录路径。 | 3542 3543**错误码:** 3544 3545接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3546 3547**示例:** 3548 3549 ```ts 3550 import { BusinessError } from '@kit.BasicServicesKit'; 3551 fs.mkdtemp(pathDir + "/XXXXXX").then((dir: string) => { 3552 console.info("mkdtemp succeed:" + dir); 3553 }).catch((err: BusinessError) => { 3554 console.error("mkdtemp failed with error message: " + err.message + ", error code: " + err.code); 3555 }); 3556 ``` 3557 3558## fs.mkdtemp 3559 3560mkdtemp(prefix: string, callback: AsyncCallback<string>): void 3561 3562创建临时目录,使用callback异步回调。 3563 3564**系统能力**:SystemCapability.FileManagement.File.FileIO 3565 3566**参数:** 3567 3568 | 参数名 | 类型 | 必填 | 说明 | 3569 | -------- | --------------------------- | ---- | --------------------------- | 3570 | prefix | string | 是 | 指定目录路径,命名时需要以"XXXXXX"作为结尾。路径末尾的"XXXXXX"字符串将被替换为随机字符,以创建唯一的目录名。 | 3571 | callback | AsyncCallback<string> | 是 | 异步创建临时目录之后的回调。 | 3572 3573**错误码:** 3574 3575接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3576 3577**示例:** 3578 3579 ```ts 3580 import { BusinessError } from '@kit.BasicServicesKit'; 3581 fs.mkdtemp(pathDir + "/XXXXXX", (err: BusinessError, res: string) => { 3582 if (err) { 3583 console.error("mkdtemp failed with error message: " + err.message + ", error code: " + err.code); 3584 } else { 3585 console.info("mkdtemp succeed"); 3586 } 3587 }); 3588 ``` 3589 3590## fs.mkdtempSync 3591 3592mkdtempSync(prefix: string): string 3593 3594以同步的方法创建临时目录。 3595 3596**系统能力**:SystemCapability.FileManagement.File.FileIO 3597 3598**参数:** 3599 3600 | 参数名 | 类型 | 必填 | 说明 | 3601 | ------ | ------ | ---- | --------------------------- | 3602 | prefix | string | 是 | 指定目录路径,命名时需要以"XXXXXX"作为结尾。路径末尾的"XXXXXX"字符串将被替换为随机字符,以创建唯一的目录名。 | 3603 3604**返回值:** 3605 3606 | 类型 | 说明 | 3607 | ------ | ---------- | 3608 | string | 产生的唯一目录路径。 | 3609 3610**错误码:** 3611 3612接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3613 3614**示例:** 3615 3616 ```ts 3617 let res = fs.mkdtempSync(pathDir + "/XXXXXX"); 3618 ``` 3619 3620## fs.utimes<sup>11+</sup> 3621 3622utimes(path: string, mtime: number): void 3623 3624修改文件最近访问时间属性。 3625 3626**系统能力**:SystemCapability.FileManagement.File.FileIO 3627 3628**参数:** 3629| 参数名 | 类型 | 必填 | 说明 | 3630| ------------ | ------ | ------ | ------------------------------------------------------------ | 3631| path | string | 是 | 文件的应用沙箱路径。 | 3632| mtime | number | 是 | 待更新的时间戳。自1970年1月1日起至目标时间的毫秒数。仅支持修改文件最近访问时间属性。 | 3633 3634**错误码:** 3635 3636接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3637 3638**示例:** 3639 3640 ```ts 3641 let filePath = pathDir + "/test.txt"; 3642 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 3643 fs.writeSync(file.fd, 'test data'); 3644 fs.closeSync(file); 3645 fs.utimes(filePath, new Date().getTime()); 3646 ``` 3647 3648## fs.createRandomAccessFile<sup>10+</sup> 3649 3650createRandomAccessFile(file: string | File, mode?: number): Promise<RandomAccessFile> 3651 3652基于文件路径或文件对象创建RandomAccessFile对象,使用promise异步回调。 3653 3654**系统能力**:SystemCapability.FileManagement.File.FileIO 3655 3656**参数:** 3657| 参数名 | 类型 | 必填 | 说明 | 3658| ------------ | ------ | ------ | ------------------------------------------------------------ | 3659| file | string \| [File](#file) | 是 | 文件的应用沙箱路径或已打开的File对象。 | 3660| mode | number | 否 | 创建文件RandomAccessFile对象的[选项](#openmode),仅当传入文件沙箱路径时生效,必须指定如下选项中的一个,默认以只读方式创建:<br/>- OpenMode.READ_ONLY(0o0):只读创建。<br/>- OpenMode.WRITE_ONLY(0o1):只写创建。<br/>- OpenMode.READ_WRITE(0o2):读写创建。<br/>给定如下功能选项,以按位或的方式追加,默认不给定任何额外选项:<br/>- OpenMode.CREATE(0o100):若文件不存在,则创建文件。<br/>- OpenMode.TRUNC(0o1000):如果RandomAccessFile对象存在且对应文件具有写权限,则将其长度裁剪为零。<br/>- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到RandomAccessFile对象末尾。<br/>- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。<br/>- OpenMode.DIR(0o200000):如果path未指向目录,则出错。不允许附加写权限。<br/>- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。<br/>- OpenMode.SYNC(0o4010000):以同步IO的方式创建RandomAccessFile对象。 | 3661 3662**返回值:** 3663 3664 | 类型 | 说明 | 3665 | --------------------------------- | --------- | 3666 | Promise<[RandomAccessFile](#randomaccessfile)> | Promise对象。返回RandomAccessFile对象的结果。 | 3667 3668**错误码:** 3669 3670接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3671 3672**示例:** 3673 3674 ```ts 3675 import { BusinessError } from '@kit.BasicServicesKit'; 3676 let filePath = pathDir + "/test.txt"; 3677 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 3678 fs.createRandomAccessFile(file).then((randomAccessFile: fs.RandomAccessFile) => { 3679 console.info("randomAccessFile fd: " + randomAccessFile.fd); 3680 randomAccessFile.close(); 3681 }).catch((err: BusinessError) => { 3682 console.error("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code); 3683 }).finally(() => { 3684 fs.closeSync(file); 3685 }); 3686 ``` 3687 3688## fs.createRandomAccessFile<sup>10+</sup> 3689 3690createRandomAccessFile(file: string | File, callback: AsyncCallback<RandomAccessFile>): void 3691 3692基于文件路径或文件对象,以只读方式创建RandomAccessFile对象,使用callback异步回调。 3693 3694**系统能力**:SystemCapability.FileManagement.File.FileIO 3695 3696**参数:** 3697 3698| 参数名 | 类型 | 必填 | 说明 | 3699| ------------ | ------ | ------ | ------------------------------------------------------------ | 3700| file | string \| [File](#file) | 是 | 文件的应用沙箱路径或已打开的File对象。 | 3701| callback | AsyncCallback<[RandomAccessFile](#randomaccessfile)> | 是 | 异步创建RandomAccessFile对象之后的回调。 | 3702 3703**错误码:** 3704 3705接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3706 3707**示例:** 3708 ```ts 3709 import { BusinessError } from '@kit.BasicServicesKit'; 3710 let filePath = pathDir + "/test.txt"; 3711 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 3712 fs.createRandomAccessFile(file, (err: BusinessError, randomAccessFile: fs.RandomAccessFile) => { 3713 if (err) { 3714 console.error("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code); 3715 } else { 3716 console.info("randomAccessFile fd: " + randomAccessFile.fd); 3717 randomAccessFile.close(); 3718 } 3719 fs.closeSync(file); 3720 }); 3721 ``` 3722 3723 ## fs.createRandomAccessFile<sup>10+</sup> 3724 3725createRandomAccessFile(file: string | File, mode: number, callback: AsyncCallback<RandomAccessFile>): void 3726 3727基于文件路径或文件对象创建RandomAccessFile对象,使用callback异步回调。 3728 3729**系统能力**:SystemCapability.FileManagement.File.FileIO 3730 3731**参数:** 3732 3733| 参数名 | 类型 | 必填 | 说明 | 3734| ------------ | ------ | ------ | ------------------------------------------------------------ | 3735| file | string \| [File](#file) | 是 | 文件的应用沙箱路径或已打开的File对象。 | 3736| mode | number | 是 | 创建文件RandomAccessFile对象的[选项](#openmode),仅当传入文件沙箱路径时生效,必须指定如下选项中的一个,默认以只读方式创建:<br/>- OpenMode.READ_ONLY(0o0):只读创建。<br/>- OpenMode.WRITE_ONLY(0o1):只写创建。<br/>- OpenMode.READ_WRITE(0o2):读写创建。<br/>给定如下功能选项,以按位或的方式追加,默认不给定任何额外选项:<br/>- OpenMode.CREATE(0o100):若文件不存在,则创建文件。<br/>- OpenMode.TRUNC(0o1000):如果RandomAccessFile对象存在且对应文件具有写权限,则将其长度裁剪为零。<br/>- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到RandomAccessFile对象末尾。<br/>- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。<br/>- OpenMode.DIR(0o200000):如果path不指向目录,则出错。不允许附加写权限。<br/>- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。<br/>- OpenMode.SYNC(0o4010000):以同步IO的方式创建RandomAccessFile对象。 | 3737| callback | AsyncCallback<[RandomAccessFile](#randomaccessfile)> | 是 | 异步创建RandomAccessFile对象之后的回调。 | 3738 3739**错误码:** 3740 3741接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3742 3743**示例:** 3744 ```ts 3745 import { BusinessError } from '@kit.BasicServicesKit'; 3746 let filePath = pathDir + "/test.txt"; 3747 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 3748 fs.createRandomAccessFile(file, fs.OpenMode.READ_ONLY, (err: BusinessError, randomAccessFile: fs.RandomAccessFile) => { 3749 if (err) { 3750 console.error("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code); 3751 } else { 3752 console.info("randomAccessFile fd: " + randomAccessFile.fd); 3753 randomAccessFile.close(); 3754 } 3755 fs.closeSync(file); 3756 }); 3757 ``` 3758 3759## fs.createRandomAccessFile<sup>12+</sup> 3760 3761createRandomAccessFile(file: string | File, mode?: number, options?: RandomAccessFileOptions): Promise<RandomAccessFile> 3762 3763基于文件路径或文件对象创建RandomAccessFile对象,使用promise异步回调。 3764 3765**系统能力**:SystemCapability.FileManagement.File.FileIO 3766 3767**参数:** 3768 3769| 参数名 | 类型 | 必填 | 说明 | 3770| ------------ | ------ | ------ | ------------------------------------------------------------ | 3771| file | string \| [File](#file) | 是 | 文件的应用沙箱路径或已打开的File对象。 | 3772| mode | number | 否 | 创建文件RandomAccessFile对象的[选项](#openmode),仅当传入文件沙箱路径时生效,必须指定如下选项中的一个,默认以只读方式创建:<br/>- OpenMode.READ_ONLY(0o0):只读创建。<br/>- OpenMode.WRITE_ONLY(0o1):只写创建。<br/>- OpenMode.READ_WRITE(0o2):读写创建。<br/>给定如下功能选项,以按位或的方式追加,默认不给定任何额外选项:<br/>- OpenMode.CREATE(0o100):若文件不存在,则创建文件。<br/>- OpenMode.TRUNC(0o1000):如果RandomAccessFile对象存在且对应文件具有写权限,则将其长度裁剪为零。<br/>- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到RandomAccessFile对象末尾。<br/>- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。<br/>- OpenMode.DIR(0o200000):如果path不指向目录,则出错。不允许附加写权限。<br/>- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。<br/>- OpenMode.SYNC(0o4010000):以同步IO的方式创建RandomAccessFile对象。 | 3773|options|[RandomAccessFileOptions](#randomaccessfileoptions12)|否|支持如下选项:<br/>- start,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读。<br/>- end,number类型,表示期望读取结束的位置。可选,默认文件末尾。| 3774 3775**返回值:** 3776 3777 | 类型 | 说明 | 3778 | --------------------------------- | --------- | 3779 | Promise<[RandomAccessFile](#randomaccessfile)> | Promise对象。返回RandomAccessFile对象的结果。 | 3780 3781**错误码:** 3782 3783接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3784 3785```ts 3786import { BusinessError } from '@kit.BasicServicesKit'; 3787let filePath = pathDir + "/test.txt"; 3788fs.createRandomAccessFile(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE, { start: 10, end: 100 }) 3789 .then((randomAccessFile: fs.RandomAccessFile) => { 3790 console.info("randomAccessFile fd: " + randomAccessFile.fd); 3791 randomAccessFile.close(); 3792 }) 3793 .catch((err: BusinessError) => { 3794 console.error("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code); 3795 }); 3796``` 3797 3798 3799## fs.createRandomAccessFileSync<sup>10+</sup> 3800 3801createRandomAccessFileSync(file: string | File, mode?: number): RandomAccessFile 3802 3803基于文件路径或文件对象创建RandomAccessFile对象。 3804 3805**系统能力**:SystemCapability.FileManagement.File.FileIO 3806 3807**参数:** 3808 3809| 参数名 | 类型 | 必填 | 说明 | 3810| ------------ | ------ | ------ | ------------------------------------------------------------ | 3811| file | string \| [File](#file) | 是 | 文件的应用沙箱路径或已打开的File对象。 | 3812| mode | number | 否 | 创建文件RandomAccessFile对象的[选项](#openmode),仅当传入文件沙箱路径时生效,必须指定如下选项中的一个,默认以只读方式创建:<br/>- OpenMode.READ_ONLY(0o0):只读创建。<br/>- OpenMode.WRITE_ONLY(0o1):只写创建。<br/>- OpenMode.READ_WRITE(0o2):读写创建。<br/>给定如下功能选项,以按位或的方式追加,默认不给定任何额外选项:<br/>- OpenMode.CREATE(0o100):若文件不存在,则创建文件。<br/>- OpenMode.TRUNC(0o1000):如果RandomAccessFile对象存在且对应文件具有写权限,则将其长度裁剪为零。<br/>- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到RandomAccessFile对象末尾。<br/>- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。<br/>- OpenMode.DIR(0o200000):如果path不指向目录,则出错。不允许附加写权限。<br/>- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。<br/>- OpenMode.SYNC(0o4010000):以同步IO的方式创建RandomAccessFile对象。 | 3813 3814**返回值:** 3815 3816 | 类型 | 说明 | 3817 | ------------------ | --------- | 3818 | [RandomAccessFile](#randomaccessfile) | 返回RandomAccessFile对象。 | 3819 3820**错误码:** 3821 3822接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3823 3824**示例:** 3825 3826 ```ts 3827 let filePath = pathDir + "/test.txt"; 3828 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 3829 let randomAccessFile = fs.createRandomAccessFileSync(file); 3830 randomAccessFile.close(); 3831 ``` 3832 3833## fs.createRandomAccessFileSync<sup>12+</sup> 3834 3835createRandomAccessFileSync(file: string | File, mode?: number, 3836 options?: RandomAccessFileOptions): RandomAccessFile 3837 3838基于文件路径或文件对象创建RandomAccessFile对象。 3839 3840**系统能力**:SystemCapability.FileManagement.File.FileIO 3841 3842**参数:** 3843 3844| 参数名 | 类型 | 必填 | 说明 | 3845| ------------ | ------ | ------ | ------------------------------------------------------------ | 3846| file | string \| [File](#file) | 是 | 文件的应用沙箱路径或已打开的File对象。 | 3847| mode | number | 否 | 创建文件RandomAccessFile对象的[选项](#openmode),仅当传入文件沙箱路径时生效,必须指定如下选项中的一个,默认以只读方式创建:<br/>- OpenMode.READ_ONLY(0o0):只读创建。<br/>- OpenMode.WRITE_ONLY(0o1):只写创建。<br/>- OpenMode.READ_WRITE(0o2):读写创建。<br/>给定如下功能选项,以按位或的方式追加,默认不给定任何额外选项:<br/>- OpenMode.CREATE(0o100):若文件不存在,则创建文件。<br/>- OpenMode.TRUNC(0o1000):如果RandomAccessFile对象存在且对应文件具有写权限,则将其长度裁剪为零。<br/>- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到RandomAccessFile对象末尾。<br/>- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。<br/>- OpenMode.DIR(0o200000):如果path不指向目录,则出错。不允许附加写权限。<br/>- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。<br/>- OpenMode.SYNC(0o4010000):以同步IO的方式创建RandomAccessFile对象。 | 3848|options|[RandomAccessFileOptions](#randomaccessfileoptions12)|否|支持如下选项:<br/>- start,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读。<br/>- end,number类型,表示期望读取结束的位置。可选,默认文件末尾。| 3849 3850**返回值:** 3851 3852 | 类型 | 说明 | 3853 | ------------------ | --------- | 3854 | [RandomAccessFile](#randomaccessfile) | 返回RandomAccessFile对象。 | 3855 3856**错误码:** 3857 3858接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3859 3860**示例:** 3861 3862 ```ts 3863 let filePath = pathDir + "/test.txt"; 3864 let randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE, 3865 { start: 10, end: 100 }); 3866 randomAccessFile.close(); 3867 ``` 3868 3869## fs.createStream 3870 3871createStream(path: string, mode: string): Promise<Stream> 3872 3873基于文件路径创建文件流,使用promise异步回调。需要配合[Stream](#stream)中的close()函数关闭文件流。 3874 3875**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 3876 3877**系统能力**:SystemCapability.FileManagement.File.FileIO 3878 3879**参数:** 3880 3881| 参数名 | 类型 | 必填 | 说明 | 3882| ------ | ------ | ---- | ------------------------------------------------------------ | 3883| path | string | 是 | 文件的应用沙箱路径。 | 3884| mode | string | 是 | - r:打开只读文件,该文件必须存在。<br/>- r+:打开可读写的文件,该文件必须存在。<br/>- w:打开只写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- w+:打开可读写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- a:以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。<br/>- a+:以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。 | 3885 3886**返回值:** 3887 3888 | 类型 | 说明 | 3889 | --------------------------------- | --------- | 3890 | Promise<[Stream](#stream)> | Promise对象。返回文件流的结果。 | 3891 3892**错误码:** 3893 3894接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3895 3896**示例:** 3897 3898 ```ts 3899 import { BusinessError } from '@kit.BasicServicesKit'; 3900 let filePath = pathDir + "/test.txt"; 3901 fs.createStream(filePath, "a+").then((stream: fs.Stream) => { 3902 stream.closeSync(); 3903 console.info("createStream succeed"); 3904 }).catch((err: BusinessError) => { 3905 console.error("createStream failed with error message: " + err.message + ", error code: " + err.code); 3906 }); 3907 ``` 3908 3909 3910## fs.createStream 3911 3912createStream(path: string, mode: string, callback: AsyncCallback<Stream>): void 3913 3914基于文件路径创建文件流,使用callback异步回调。需要配合[Stream](#stream)中的close()函数关闭文件流。 3915 3916**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 3917 3918**系统能力**:SystemCapability.FileManagement.File.FileIO 3919 3920**参数:** 3921 3922| 参数名 | 类型 | 必填 | 说明 | 3923| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | 3924| path | string | 是 | 文件的应用沙箱路径。 | 3925| mode | string | 是 | - r:打开只读文件,该文件必须存在。<br/>- r+:打开可读写的文件,该文件必须存在。<br/>- w:打开只写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- w+:打开可读写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- a:以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。<br/>- a+:以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。 | 3926| callback | AsyncCallback<[Stream](#stream)> | 是 | 异步打开文件流之后的回调。 | 3927 3928**错误码:** 3929 3930接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3931 3932**示例:** 3933 3934 ```ts 3935 import { BusinessError } from '@kit.BasicServicesKit'; 3936 let filePath = pathDir + "/test.txt"; 3937 fs.createStream(filePath, "r+", (err: BusinessError, stream: fs.Stream) => { 3938 if (err) { 3939 console.error("create stream failed with error message: " + err.message + ", error code: " + err.code); 3940 } else { 3941 stream.closeSync(); 3942 console.info("createStream succeed"); 3943 } 3944 }) 3945 ``` 3946 3947## fs.createStreamSync 3948 3949createStreamSync(path: string, mode: string): Stream 3950 3951以同步方法基于文件路径创建文件流。需要配合[Stream](#stream)中的close()函数关闭文件流。 3952 3953**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 3954 3955**系统能力**:SystemCapability.FileManagement.File.FileIO 3956 3957**参数:** 3958 3959| 参数名 | 类型 | 必填 | 说明 | 3960| ------ | ------ | ---- | ------------------------------------------------------------ | 3961| path | string | 是 | 文件的应用沙箱路径。 | 3962| mode | string | 是 | - r:打开只读文件,该文件必须存在。<br/>- r+:打开可读写的文件,该文件必须存在。<br/>- w:打开只写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- w+:打开可读写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- a:以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。<br/>- a+:以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。 | 3963 3964**返回值:** 3965 3966 | 类型 | 说明 | 3967 | ------------------ | --------- | 3968 | [Stream](#stream) | 返回文件流的结果。 | 3969 3970**错误码:** 3971 3972接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3973 3974**示例:** 3975 3976 ```ts 3977 let filePath = pathDir + "/test.txt"; 3978 let stream = fs.createStreamSync(filePath, "r+"); 3979 console.info("createStream succeed"); 3980 stream.closeSync(); 3981 ``` 3982 3983 3984## fs.fdopenStream 3985 3986fdopenStream(fd: number, mode: string): Promise<Stream> 3987 3988基于文件描述符打开文件流,使用promise异步回调。需要配合[Stream](#stream)中的close()函数关闭文件流。 3989 3990**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 3991 3992**系统能力**:SystemCapability.FileManagement.File.FileIO 3993 3994**参数:** 3995 3996 | 参数名 | 类型 | 必填 | 说明 | 3997 | ---- | ------ | ---- | ---------------------------------------- | 3998 | fd | number | 是 | 已打开的文件描述符。 | 3999 | mode | string | 是 | - r:打开只读文件,该文件必须存在。<br/>- r+:打开可读写的文件,该文件必须存在。<br/>- w:打开只写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- w+:打开可读写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- a:以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。<br/>- a+:以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。 | 4000 4001**返回值:** 4002 4003 | 类型 | 说明 | 4004 | --------------------------------- | --------- | 4005 | Promise<[Stream](#stream)> | Promise对象。返回文件流的结果。 | 4006 4007**错误码:** 4008 4009接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4010 4011**示例:** 4012 4013 ```ts 4014 import { BusinessError } from '@kit.BasicServicesKit'; 4015 let filePath = pathDir + "/test.txt"; 4016 let file = fs.openSync(filePath); 4017 fs.fdopenStream(file.fd, "r+").then((stream: fs.Stream) => { 4018 console.info("openStream succeed"); 4019 stream.closeSync(); 4020 }).catch((err: BusinessError) => { 4021 console.error("openStream failed with error message: " + err.message + ", error code: " + err.code); 4022 // 文件流打开失败后,文件描述符需要手动关闭 4023 fs.closeSync(file); 4024 }); 4025 ``` 4026 4027> **注意:** 4028> 4029> 使用文件描述符创建的文件流时,文件描述符的生命周期将由文件流对象管理。调用文件流的close()函数后,初始的文件描述符也会被关闭。 4030 4031## fs.fdopenStream 4032 4033fdopenStream(fd: number, mode: string, callback: AsyncCallback<Stream>): void 4034 4035基于文件描述符打开文件流,使用callback异步回调。需要配合[Stream](#stream)中的close()函数关闭文件流。 4036 4037**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 4038 4039**系统能力**:SystemCapability.FileManagement.File.FileIO 4040 4041**参数:** 4042 4043 | 参数名 | 类型 | 必填 | 说明 | 4044 | -------- | ---------------------------------------- | ---- | ---------------------------------------- | 4045 | fd | number | 是 | 已打开的文件描述符。 | 4046 | mode | string | 是 | - r:打开只读文件,该文件必须存在。<br/>- r+:打开可读写的文件,该文件必须存在。<br/>- w:打开只写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- w+:打开可读写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- a:以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。<br/>- a+:以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。 | 4047 | callback | AsyncCallback<[Stream](#stream)> | 是 | 异步打开文件流之后的回调。 | 4048 4049**错误码:** 4050 4051接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4052 4053**示例:** 4054 4055 ```ts 4056 import { BusinessError } from '@kit.BasicServicesKit'; 4057 let filePath = pathDir + "/test.txt"; 4058 let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); 4059 fs.fdopenStream(file.fd, "r+", (err: BusinessError, stream: fs.Stream) => { 4060 if (err) { 4061 console.error("fdopen stream failed with error message: " + err.message + ", error code: " + err.code); 4062 // 文件流打开失败后,文件描述符需要手动关闭 4063 fs.closeSync(file); 4064 } else { 4065 console.info("fdopen stream succeed"); 4066 stream.closeSync(); 4067 } 4068 }); 4069 ``` 4070 4071> **注意:** 4072> 4073> 使用文件描述符创建的文件流,文件描述符的生命周期也交由文件流对象,在调用文件流的close()函数后,初始的文件描述符也会被关闭。 4074 4075## fs.fdopenStreamSync 4076 4077fdopenStreamSync(fd: number, mode: string): Stream 4078 4079以同步方法基于文件描述符打开文件流。需要配合[Stream](#stream)中的close()函数关闭文件流。 4080 4081**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 4082 4083**系统能力**:SystemCapability.FileManagement.File.FileIO 4084 4085**参数:** 4086 4087 | 参数名 | 类型 | 必填 | 说明 | 4088 | ---- | ------ | ---- | ---------------------------------------- | 4089 | fd | number | 是 | 已打开的文件描述符。 | 4090 | mode | string | 是 | - r:打开只读文件,该文件必须存在。<br/>- r+:打开可读写的文件,该文件必须存在。<br/>- w:打开只写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- w+:打开可读写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- a:以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。<br/>- a+:以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。 | 4091 4092**返回值:** 4093 4094 | 类型 | 说明 | 4095 | ------------------ | --------- | 4096 | [Stream](#stream) | 返回文件流的结果。 | 4097 4098**错误码:** 4099 4100接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4101 4102**示例:** 4103 4104 ```ts 4105 let filePath = pathDir + "/test.txt"; 4106 let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY | fs.OpenMode.CREATE); 4107 let stream = fs.fdopenStreamSync(file.fd, "r+"); 4108 stream.closeSync(); 4109 ``` 4110 4111> **注意:** 4112> 4113> 使用文件描述符创建的文件流,文件描述符的生命周期也交由文件流对象,在调用文件流的close()函数后,初始的文件描述符也会被关闭。 4114 4115## fs.createReadStream<sup>12+</sup> 4116 4117createReadStream(path: string, options?: ReadStreamOptions ): ReadStream 4118 4119以同步方法打开文件可读流。 4120 4121**系统能力**:SystemCapability.FileManagement.File.FileIO 4122 4123**参数:** 4124 4125 | 参数名 | 类型 | 必填 | 说明 | 4126 | ---- | ------ | ---- | ---------------------------------------- | 4127 | path | string | 是 | 文件路径。 | 4128 | options | [ReadStreamOptions](#readstreamoptions12) | 否 | 支持如下选项:<br/>- start,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读。<br/>- end,number类型,表示期望读取结束的位置。可选,默认文件末尾。 | 4129 4130**返回值:** 4131 4132 | 类型 | 说明 | 4133 | ------------------ | --------- | 4134 | [ReadStream](#readstream12) | 文件可读流。 | 4135 4136**错误码:** 4137 4138接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4139 4140**示例:** 4141 4142 ```ts 4143 // 创建文件可读流 4144 const rs = fs.createReadStream(`${pathDir}/read.txt`); 4145 // 创建文件可写流 4146 const ws = fs.createWriteStream(`${pathDir}/write.txt`); 4147 // 暂停模式拷贝文件 4148 rs.on('readable', () => { 4149 const data = rs.read(); 4150 if (!data) { 4151 return; 4152 } 4153 ws.write(data); 4154 }); 4155 ``` 4156 4157## fs.createWriteStream<sup>12+</sup> 4158 4159createWriteStream(path: string, options?: WriteStreamOptions): WriteStream 4160 4161以同步方法打开文件可写流。 4162 4163**系统能力**:SystemCapability.FileManagement.File.FileIO 4164 4165**参数:** 4166 4167 | 参数名 | 类型 | 必填 | 说明 | 4168 | ---- | ------ | ---- | ---------------------------------------- | 4169 | path | string | 是 | 文件路径。 | 4170 | options | [WriteStreamOptions](#writestreamoptions12) | 否 | 支持如下选项:<br/>- start,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写。<br/>- mode,number 类型,创建文件可写流的[选项](#openmode),可选,默认以只写方式创建。 | 4171 4172**返回值:** 4173 4174 | 类型 | 说明 | 4175 | ------------------ | --------- | 4176 | [WriteStream](#writestream12) | 文件可写流。 | 4177 4178**错误码:** 4179 4180接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4181 4182**示例:** 4183 4184 ```ts 4185 // 创建文件可读流 4186 const rs = fs.createReadStream(`${pathDir}/read.txt`); 4187 // 创建文件可写流 4188 const ws = fs.createWriteStream(`${pathDir}/write.txt`); 4189 // 暂停模式拷贝文件 4190 rs.on('readable', () => { 4191 const data = rs.read(); 4192 if (!data) { 4193 return; 4194 } 4195 ws.write(data); 4196 }); 4197 ``` 4198 4199## AtomicFile<sup>15+</sup> 4200AtomicFile是一个用于对文件进行原子读写操作的类。 4201 4202在写操作时,通过写入临时文件,并在写入成功后将其重命名到原始文件位置来确保写入文件的完整性;而在写入失败时删除临时文件,不修改原始文件内容。 4203 4204使用者可以自行调用finishWrite或failWrite来完成文件内容的写入或回滚。 4205 4206**系统能力**:SystemCapability.FileManagement.File.FileIO 4207 4208### constructor<sup>15+</sup> 4209 4210constructor(path: string) 4211 4212对于给定路径的文件创建一个AtomicFile类。 4213 4214**系统能力**:SystemCapability.FileManagement.File.FileIO 4215 4216**参数:** 4217 4218 | 参数名 | 类型 | 必填 | 说明 | 4219 | ------ | ------ | ---- | -------------------------------------- | 4220 | path | string | 是 | 文件的沙箱路径。 | 4221 4222### getBaseFile<sup>15+</sup> 4223 4224getBaseFile(): File 4225 4226通过AtomicFile对象获取文件对象。 4227 4228文件描述符fd需要由用户调用close方法关闭。 4229 4230**系统能力**:SystemCapability.FileManagement.File.FileIO 4231 4232**返回值:** 4233 4234 | 类型 | 说明 | 4235 | ------------- | -------------- | 4236 | [File](#file) | 打开的File对象。| 4237 4238**错误码:** 4239 4240接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)和[通用错误码](../errorcode-universal.md)。 4241 4242**示例:** 4243 4244<!--code_no_check--> 4245```ts 4246import { common } from '@kit.AbilityKit'; 4247import { fileIo as fs} from '@kit.CoreFileKit'; 4248 4249// 请在组件内获取context,确保this.getUIContext().getHostContext()返回结果为UIAbilityContext 4250let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 4251let pathDir = context.filesDir; 4252 4253try { 4254 let atomicFile = new fs.AtomicFile(`${pathDir}/write.txt`); 4255 let writeStream = atomicFile.startWrite(); 4256 writeStream.write("hello, world", "utf-8", ()=> { 4257 atomicFile.finishWrite(); 4258 let File = atomicFile.getBaseFile(); 4259 console.info('AtomicFile getBaseFile File.fd is: ' + File.fd + ' path: ' + File.path + ' name: ' + File.name); 4260 }) 4261} catch (err) { 4262 console.error(`Failed to get baseFile. Code: ${err.code}, message: ${err.message}`); 4263} 4264``` 4265 4266### openRead<sup>15+</sup> 4267 4268openRead(): ReadStream 4269 4270创建一个读文件流。 4271 4272**系统能力**:SystemCapability.FileManagement.File.FileIO 4273 4274**返回值:** 4275 4276 | 类型 | 说明 | 4277 | ------------------ | --------- | 4278 | [ReadStream](#readstream12) | 文件可读流。 | 4279 4280**错误码:** 4281 4282接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)和[通用错误码](../errorcode-universal.md)。 4283 4284**示例:** 4285 4286<!--code_no_check--> 4287```ts 4288import { common } from '@kit.AbilityKit'; 4289import { fileIo as fs} from '@kit.CoreFileKit'; 4290 4291// 请在组件内获取context,确保this.getUIContext().getHostContext()返回结果为UIAbilityContext 4292let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 4293let pathDir = context.filesDir; 4294 4295try { 4296 let file = new fs.AtomicFile(`${pathDir}/read.txt`); 4297 let writeStream = file.startWrite(); 4298 writeStream.write("hello, world", "utf-8", ()=> { 4299 file.finishWrite(); 4300 setTimeout(()=>{ 4301 let readStream = file.openRead(); 4302 readStream.on('readable', () => { 4303 const data = readStream.read(); 4304 if (!data) { 4305 console.error('AtomicFile read data is null.'); 4306 return; 4307 } 4308 console.info('AtomicFile read data is: ' + data); 4309 }); 4310 },1000); 4311 }) 4312} catch (err) { 4313 console.error(`Failed to AtomicFile. Code: ${err.code}, message: ${err.message}`); 4314} 4315``` 4316 4317### readFully<sup>15+</sup> 4318 4319readFully(): ArrayBuffer 4320 4321读取文件全部内容。 4322 4323**系统能力**:SystemCapability.FileManagement.File.FileIO 4324 4325**返回值:** 4326 4327 | 类型 | 说明 | 4328 | ------------------ | --------- | 4329 | ArrayBuffer | 文件的全部内容。 | 4330 4331**错误码:** 4332 4333接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)和[通用错误码](../errorcode-universal.md)。 4334 4335**示例:** 4336 4337<!--code_no_check--> 4338```ts 4339import { common } from '@kit.AbilityKit'; 4340import { fileIo as fs} from '@kit.CoreFileKit'; 4341import { util, buffer } from '@kit.ArkTS'; 4342 4343// 请在组件内获取context,确保this.getUIContext().getHostContext()返回结果为UIAbilityContext 4344let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 4345let pathDir = context.filesDir; 4346 4347try { 4348 let file = new fs.AtomicFile(`${pathDir}/read.txt`); 4349 let writeStream = file.startWrite(); 4350 writeStream.write("hello, world", "utf-8", ()=> { 4351 file.finishWrite(); 4352 setTimeout(()=>{ 4353 let data = file.readFully(); 4354 let decoder = util.TextDecoder.create('utf-8'); 4355 let str = decoder.decodeToString(new Uint8Array(data)); 4356 console.info('AtomicFile readFully str is: ' + str); 4357 },1000); 4358 }) 4359} catch (err) { 4360 console.error(`Failed to AtomicFile. Code: ${err.code}, message: ${err.message}`); 4361} 4362``` 4363 4364### startWrite<sup>15+</sup> 4365 4366startWrite(): WriteStream 4367 4368对文件开始新的写入操作。将返回一个WriteStream,用于在其中写入新的文件数据。 4369 4370当文件不存在时新建文件。 4371 4372在写入文件完成后,写入成功需要调用finishWrite(),写入失败需要调用failWrite()。 4373 4374**系统能力**:SystemCapability.FileManagement.File.FileIO 4375 4376**返回值:** 4377 4378 | 类型 | 说明 | 4379 | ------------------ | --------- | 4380 | [WriteStream](#writestream12) | 文件可写流。 | 4381 4382**错误码:** 4383 4384接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)和[通用错误码](../errorcode-universal.md)。 4385 4386**示例:** 4387 4388<!--code_no_check--> 4389```ts 4390import { common } from '@kit.AbilityKit'; 4391import { fileIo as fs} from '@kit.CoreFileKit'; 4392 4393// 请在组件内获取context,确保this.getUIContext().getHostContext()返回结果为UIAbilityContext 4394let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 4395let pathDir = context.filesDir; 4396 4397try { 4398 let file = new fs.AtomicFile(`${pathDir}/write.txt`); 4399 let writeStream = file.startWrite(); 4400 writeStream.write("hello, world", "utf-8", ()=> { 4401 console.info('AtomicFile write finished!'); 4402 }) 4403} catch (err) { 4404 console.error(`Failed to AtomicFile. Code: ${err.code}, message: ${err.message}`); 4405} 4406``` 4407 4408### finishWrite<sup>15+</sup> 4409 4410finishWrite(): void 4411 4412在完成对startWrite返回流的写入操作时调用,表示文件写入成功。 4413 4414**系统能力**:SystemCapability.FileManagement.File.FileIO 4415 4416**错误码:** 4417 4418接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)和[通用错误码](../errorcode-universal.md)。 4419 4420**示例:** 4421 4422<!--code_no_check--> 4423```ts 4424import { common } from '@kit.AbilityKit'; 4425import { fileIo as fs} from '@kit.CoreFileKit'; 4426 4427// 请在组件内获取context,确保this.getUIContext().getHostContext()返回结果为UIAbilityContext 4428let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 4429let pathDir = context.filesDir; 4430 4431try { 4432 let file = new fs.AtomicFile(`${pathDir}/write.txt`); 4433 let writeStream = file.startWrite(); 4434 writeStream.write("hello, world", "utf-8", ()=> { 4435 file.finishWrite(); 4436 }) 4437} catch (err) { 4438 console.error(`Failed to AtomicFile. Code: ${err.code}, message: ${err.message}`); 4439} 4440``` 4441 4442### failWrite<sup>15+</sup> 4443 4444failWrite(): void 4445 4446文件写入失败后调用,将执行文件回滚操作。 4447 4448**系统能力**:SystemCapability.FileManagement.File.FileIO 4449 4450**错误码:** 4451 4452接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)和[通用错误码](../errorcode-universal.md)。 4453 4454**示例:** 4455 4456<!--code_no_check--> 4457```ts 4458import { common } from '@kit.AbilityKit'; 4459import { fileIo as fs} from '@kit.CoreFileKit'; 4460 4461// 请在组件内获取context,确保this.getUIContext().getHostContext()返回结果为UIAbilityContext 4462let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 4463let pathDir = context.filesDir; 4464 4465let file = new fs.AtomicFile(`${pathDir}/write.txt`); 4466try { 4467 let writeSream = file.startWrite(); 4468 writeSream.write("hello, world", "utf-8", ()=> { 4469 console.info('AtomicFile write succeed!'); 4470 }) 4471} catch (err) { 4472 file.failWrite(); 4473 console.error(`Failed to AtomicFile. Code: ${err.code}, message: ${err.message}`); 4474} 4475``` 4476 4477### delete<sup>15+</sup> 4478 4479delete(): void 4480 4481删除AtomicFile类,会删除原始文件和临时文件。 4482 4483**系统能力**:SystemCapability.FileManagement.File.FileIO 4484 4485**错误码:** 4486 4487接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)和[通用错误码](../errorcode-universal.md)。 4488 4489**示例:** 4490 4491<!--code_no_check--> 4492```ts 4493import { common } from '@kit.AbilityKit'; 4494import { fileIo as fs} from '@kit.CoreFileKit'; 4495import { util } from '@kit.ArkTS'; 4496 4497// 请在组件内获取context,确保this.getUIContext().getHostContext()返回结果为UIAbilityContext 4498let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 4499let pathDir = context.filesDir; 4500 4501try { 4502 let file = new fs.AtomicFile(`${pathDir}/read.txt`); 4503 let writeStream = file.startWrite(); 4504 writeStream.write("hello, world", "utf-8", ()=> { 4505 file.finishWrite(); 4506 setTimeout(()=>{ 4507 let data = file.readFully(); 4508 let decoder = util.TextDecoder.create('utf-8'); 4509 let str = decoder.decodeToString(new Uint8Array(data)); 4510 console.info('AtomicFile readFully str is: ' + str); 4511 file.delete(); 4512 },1000); 4513 }) 4514} catch (err) { 4515 console.error(`Failed to AtomicFile. Code: ${err.code}, message: ${err.message}`); 4516} 4517``` 4518 4519## fs.createWatcher<sup>10+</sup> 4520 4521createWatcher(path: string, events: number, listener: WatchEventListener): Watcher 4522 4523创建Watcher对象,监听文件或目录变动。 4524 4525**系统能力**:SystemCapability.FileManagement.File.FileIO 4526 4527**参数:** 4528 4529 | 参数名 | 类型 | 必填 | 说明 | 4530 | ---- | ------ | ---- | ---------------------------------------- | 4531 | path | string | 是 | 监听文件或目录的沙箱路径。 | 4532 | events | number | 是 | 监听变动的事件集,多个事件通过或(\|)的方式进行集合。<br/>- 0x1: IN_ACCESS, 文件被访问。<br/>- 0x2: IN_MODIFY,文件内容被修改。<br/>- 0x4: IN_ATTRIB,文件元数据被修改。<br/>- 0x8: IN_CLOSE_WRITE,文件在打开时进行了写操作,然后被关闭。<br/>- 0x10: IN_CLOSE_NOWRITE,文件或目录在打开时未进行写操作,然后被关闭。<br/>- 0x20: IN_OPEN,文件或目录被打开。 <br/>- 0x40: IN_MOVED_FROM,监听目录中文件被移动走。<br/>- 0x80: IN_MOVED_TO,监听目录中文件被移动过来。<br/>- 0x100: IN_CREATE,监听目录中文件或子目录被创建。<br/>- 0x200: IN_DELETE,监听目录中文件或子目录被删除。<br/>- 0x400: IN_DELETE_SELF,监听的目录被删除,删除后监听停止。<br/>- 0x800: IN_MOVE_SELF,监听的文件或目录被移动,移动后监听继续。<br/>- 0xfff: IN_ALL_EVENTS,监听以上所有事件。| 4533 | listener | [WatchEventListener](#watcheventlistener10) | 是 | 监听事件发生后的回调。监听事件每发生一次,回调一次。 | 4534 4535**返回值:** 4536 4537 | 类型 | 说明 | 4538 | ------------------ | --------- | 4539 | [Watcher](#watcher10) | 返回Watcher对象。 | 4540 4541**错误码:** 4542 4543接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4544 4545**示例:** 4546 4547<!--code_no_check--> 4548 ```ts 4549 import { common } from '@kit.AbilityKit'; 4550 import { fileIo as fs, WatchEvent } from '@kit.CoreFileKit'; 4551 4552 // 请在组件内获取context,确保this.getUIContext().getHostContext()返回结果为UIAbilityContext 4553 let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 4554 let pathDir = context.filesDir; 4555 let filePath = pathDir + "/test.txt"; 4556 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 4557 let watcher = fs.createWatcher(filePath, 0x2 | 0x10, (watchEvent: WatchEvent) => { 4558 if (watchEvent.event == 0x2) { 4559 console.info(watchEvent.fileName + 'was modified'); 4560 } else if (watchEvent.event == 0x10) { 4561 console.info(watchEvent.fileName + 'was closed'); 4562 } 4563 }); 4564 watcher.start(); 4565 fs.writeSync(file.fd, 'test'); 4566 fs.closeSync(file); 4567 watcher.stop(); 4568 ``` 4569 4570## WatchEventListener<sup>10+</sup> 4571 4572(event: WatchEvent): void 4573 4574事件监听类。 4575 4576**系统能力**:SystemCapability.FileManagement.File.FileIO 4577 4578**参数:** 4579 4580 | 参数名 | 类型 | 必填 | 说明 | 4581 | ---- | ------ | ---- | ---------------------------------------- | 4582 | event | [WatchEvent](#watchevent10) | 是 | 回调的事件类。 | 4583 4584## WatchEvent<sup>10+</sup> 4585 4586事件类 4587 4588**系统能力**:SystemCapability.FileManagement.File.FileIO 4589 4590### 属性 4591 4592| 名称 | 类型 | 只读 | 可选 | 说明 | 4593| ---- | ------ | ---- | ---- | ------- | 4594| fileName | string | 是 | 否 | 发生监听事件对应文件的沙箱路径,该沙箱路径包含文件名称。 | 4595| event | number | 是 | 否 | 监听变动的事件集,多个事件通过或(\|)的方式进行集合。<br/>- 0x1: IN_ACCESS, 文件被访问。<br/>- 0x2: IN_MODIFY,文件内容被修改。<br/>- 0x4: IN_ATTRIB,文件元数据被修改。<br/>- 0x8: IN_CLOSE_WRITE,文件在打开时进行了写操作,然后被关闭。<br/>- 0x10: IN_CLOSE_NOWRITE,文件或目录在打开时未进行写操作,然后被关闭。<br/>- 0x20: IN_OPEN,文件或目录被打开。 <br/>- 0x40: IN_MOVED_FROM,监听目录中文件被移动走。<br/>- 0x80: IN_MOVED_TO,监听目录中文件被移动过来。<br/>- 0x100: IN_CREATE,监听目录中文件或子目录被创建。<br/>- 0x200: IN_DELETE,监听目录中文件或子目录被删除。<br/>- 0x400: IN_DELETE_SELF,监听的目录被删除,删除后监听停止。<br/>- 0x800: IN_MOVE_SELF,监听的文件或目录被移动,移动后监听继续。<br/>- 0xfff: IN_ALL_EVENTS,监听以上所有事件。 | 4596| cookie | number | 是 | 否 | 绑定相关事件的cookie。当前仅支持事件IN_MOVED_FROM与IN_MOVED_TO,同一个文件的移动事件IN_MOVED_FROM和IN_MOVED_TO具有相同的cookie值。 | 4597 4598## Progress<sup>11+</sup> 4599 4600拷贝进度回调数据 4601 4602**系统能力**:SystemCapability.FileManagement.File.FileIO 4603 4604| 名称 | 类型 | 只读 | 可选 | 说明 | 4605| ---- | ------ | ---- | ---- | ------- | 4606| processedSize | number | 是 | 否 | 已拷贝的数据大小。 | 4607| totalSize | number | 是 | 否 | 待拷贝的数据总大小。 | 4608 4609## TaskSignal<sup>12+</sup> 4610 4611拷贝中断信号。 4612 4613**系统能力**:SystemCapability.FileManagement.File.FileIO 4614 4615### cancel<sup>12+</sup> 4616 4617cancel(): void 4618 4619取消拷贝任务。 4620 4621**系统能力**:SystemCapability.FileManagement.File.FileIO 4622 4623**错误码:** 4624 4625接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4626 4627**示例:** 4628 4629<!--code_no_check--> 4630```ts 4631import { BusinessError } from '@kit.BasicServicesKit'; 4632import { fileIo as fs } from '@kit.CoreFileKit'; 4633import { fileUri } from '@kit.CoreFileKit'; 4634import common from '@ohos.app.ability.common'; 4635 4636// 请在组件内获取context,确保this.getUIContext().getHostContext()返回结果为UIAbilityContext 4637let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 4638let pathDir = context.filesDir; 4639 4640let srcDirPathLocal: string = pathDir + "/src"; 4641let dstDirPathLocal: string = pathDir + "/dest"; 4642let srcDirUriLocal: string = fileUri.getUriFromPath(srcDirPathLocal); 4643let dstDirUriLocal: string = fileUri.getUriFromPath(dstDirPathLocal); 4644let copySignal = new fs.TaskSignal; 4645let progressListener: fs.ProgressListener = (progress: fs.Progress) => { 4646 console.info(`progressSize: ${progress.processedSize}, totalSize: ${progress.totalSize}`); 4647 if (progress.processedSize / progress.totalSize > 0.5) { 4648 copySignal.cancel(); 4649 console.info("copy cancel."); 4650 } 4651}; 4652let options: fs.CopyOptions = { 4653 "progressListener" : progressListener, 4654 "copySignal" : copySignal, 4655} 4656 4657try { 4658 fs.copy(srcDirUriLocal, dstDirUriLocal, options, (err: BusinessError) => { 4659 if (err) { 4660 console.error("copy fail, err: ", err.message); 4661 return; 4662 } 4663 console.info("copy success."); 4664 }) 4665} catch (err) { 4666 console.error("copyFileWithCancel failed, err: ", err.message); 4667} 4668 4669``` 4670 4671### onCancel<sup>12+</sup> 4672 4673onCancel(): Promise<string> 4674 4675取消拷贝事件监听。 4676 4677**系统能力**:SystemCapability.FileManagement.File.FileIO 4678 4679**返回值:** 4680 4681 | 类型 | 说明 | 4682 | --------------------- | ---------- | 4683 | Promise<string> | Promise对象。最后一个拷贝的文件路径。 | 4684 4685**错误码:** 4686 4687接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4688 4689**示例:** 4690 4691```ts 4692import { fileIo as fs } from '@kit.CoreFileKit'; 4693import { TaskSignal } from '@ohos.file.fs'; 4694let copySignal: fs.TaskSignal = new TaskSignal(); 4695copySignal.onCancel(); 4696``` 4697 4698## CopyOptions<sup>11+</sup> 4699 4700拷贝进度回调监听 4701 4702**系统能力**:SystemCapability.FileManagement.File.FileIO 4703 4704| 名称 | 类型 | 只读 | 可选 | 说明 | 4705| ---- | ------ | ---- | ---- | ------- | 4706| progressListener | [ProgressListener](#progresslistener11) | 否 | 是 | 拷贝进度监听。 | 4707| copySignal | [TaskSignal](#tasksignal12) | 否 | 是 | 取消拷贝信号。 | 4708 4709## ProgressListener<sup>11+</sup> 4710 4711拷贝进度监听。 4712 4713**系统能力**:SystemCapability.FileManagement.File.FileIO 4714 4715| 类型 | 说明 | 4716| ----| ------| 4717|(progress: [Progress](#progress11)) => void| 拷贝进度监听| 4718 4719**示例:** 4720 4721 ```ts 4722 import { TaskSignal } from '@kit.CoreFileKit'; 4723 let copySignal: fs.TaskSignal = new TaskSignal(); 4724 let progressListener: fs.ProgressListener = (progress: fs.Progress) => { 4725 console.info(`processedSize: ${progress.processedSize}, totalSize: ${progress.totalSize}`); 4726 }; 4727 let copyOption: fs.CopyOptions = { 4728 "progressListener" : progressListener, 4729 "copySignal" : copySignal, 4730 } 4731 ``` 4732 4733## Stat 4734 4735文件具体信息,在调用Stat的方法前,需要先通过[stat()](#fsstat)方法(同步或异步)构建一个Stat实例。 4736 4737**系统能力**:SystemCapability.FileManagement.File.FileIO 4738 4739### 属性 4740 4741| 名称 | 类型 | 只读 | 可选 | 说明 | 4742| ------ | ------ | ---- | ---- | ---------------------------------------- | 4743| ino | bigint | 是 | 否 | 标识该文件。通常同设备上的不同文件的INO不同。| | 4744| mode | number | 是 | 否 | 表示文件权限,各特征位的含义如下:<br/>**说明**:以下值为八进制,取得的返回值为十进制,请换算后查看。<br/>- 0o400:用户读。对于普通文件,所有者可读取文件;对于目录,所有者可读取目录项。<br/>- 0o200:用户写。对于普通文件,所有者可写入文件;对于目录,所有者可创建/删除目录项。<br/>- 0o100:用户执行。对于普通文件,所有者可执行文件;对于目录,所有者可在目录中搜索给定路径名。<br/>- 0o040:用户组读。对于普通文件,所有用户组可读取文件;对于目录,所有用户组可读取目录项。<br/>- 0o020:用户组写。对于普通文件,所有用户组可写入文件;对于目录,所有用户组可创建/删除目录项。<br/>- 0o010:用户组执行。对于普通文件,所有用户组可执行文件;对于目录,所有用户组是否可在目录中搜索给定路径名。<br/>- 0o004:其他读。对于普通文件,其余用户可读取文件;对于目录,其他用户组可读取目录项。<br/>- 0o002:其他写。对于普通文件,其余用户可写入文件;对于目录,其他用户组可创建/删除目录项。<br/>- 0o001:其他执行。对于普通文件,其余用户可执行文件;对于目录,其他用户组可在目录中搜索给定路径名。<br>**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 | 4745| uid | number | 是 | 否 | 文件所有者的ID。| 4746| gid | number | 是 | 否 | 文件所有组的ID。| 4747| size | number | 是 | 否 | 文件的大小,以字节为单位。仅对普通文件有效。 <br>**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 | 4748| atime | number | 是 | 否 | 上次访问该文件的时间,表示距1970年1月1日0时0分0秒的秒数。<br>**注意**:目前用户数据分区默认以“noatime”方式挂载,atime更新被禁用。 <br>**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 | 4749| mtime | number | 是 | 否 | 上次修改该文件的时间,表示距1970年1月1日0时0分0秒的秒数。 <br>**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 | 4750| ctime | number | 是 | 否 | 最近改变文件状态的时间,表示距1970年1月1日0时0分0秒的秒数。 | 4751| atimeNs<sup>15+</sup> | bigint | 是 | 是 | 上次访问该文件的时间,表示距1970年1月1日0时0分0秒的纳秒数。<br>**注意**:目前用户数据分区默认以“noatime”方式挂载,atime更新被禁用。 | 4752| mtimeNs<sup>15+</sup> | bigint | 是 | 是 | 上次修改该文件的时间,表示距1970年1月1日0时0分0秒的纳秒数。 | 4753| ctimeNs<sup>15+</sup> | bigint | 是 | 是 | 最近改变文件状态的时间,表示距1970年1月1日0时0分0秒的纳秒数。 | 4754| location<sup>11+</sup> | [LocaltionType](#locationtype11)| 是 |否| 文件的位置,表示该文件是本地文件或者云端文件。 4755 4756> **说明:** 4757> 4758> Stat中部分属性仅支持普通文件获取,开发者可通过[isFile()](#isfile)接口判断文件是否为普通文件。 4759 4760### isBlockDevice 4761 4762isBlockDevice(): boolean 4763 4764用于判断文件是否是块特殊文件。一个块特殊文件只能以块为粒度进行访问,且访问的时候带缓存。 4765 4766**系统能力**:SystemCapability.FileManagement.File.FileIO 4767 4768**返回值:** 4769 4770 | 类型 | 说明 | 4771 | ------- | ---------------- | 4772 | boolean | 表示文件是否是块特殊设备。true:是块特殊设备;false:不是块特殊设备。 | 4773 4774**错误码:** 4775 4776接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4777 4778**示例:** 4779 4780 ```ts 4781 let filePath = pathDir + "/test.txt"; 4782 let isBLockDevice = fs.statSync(filePath).isBlockDevice(); 4783 ``` 4784 4785### isCharacterDevice 4786 4787isCharacterDevice(): boolean 4788 4789判断文件是否为字符特殊文件。字符特殊设备支持随机访问,且访问时无缓存。 4790 4791**系统能力**:SystemCapability.FileManagement.File.FileIO 4792 4793**返回值:** 4794 4795 | 类型 | 说明 | 4796 | ------- | ----------------- | 4797 | boolean | 表示文件是否是字符特殊设备。true:是字符特殊设备;false:不是字符特殊设备。 | 4798 4799**错误码:** 4800 4801接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4802 4803**示例:** 4804 4805 ```ts 4806 let filePath = pathDir + "/test.txt"; 4807 let isCharacterDevice = fs.statSync(filePath).isCharacterDevice(); 4808 ``` 4809 4810### isDirectory 4811 4812isDirectory(): boolean 4813 4814判断文件是否为目录。 4815 4816**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 4817 4818**系统能力**:SystemCapability.FileManagement.File.FileIO 4819 4820**返回值:** 4821 4822 | 类型 | 说明 | 4823 | ------- | ------------- | 4824 | boolean | 表示文件是否是目录。true:是目录;false:不是目录。| 4825 4826**错误码:** 4827 4828接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4829 4830**示例:** 4831 4832 ```ts 4833 let dirPath = pathDir + "/test"; 4834 let isDirectory = fs.statSync(dirPath).isDirectory(); 4835 ``` 4836 4837### isFIFO 4838 4839isFIFO(): boolean 4840 4841用于判断文件是否是命名管道(有时也称为FIFO)。命名管道通常用于进程间通信。 4842 4843**系统能力**:SystemCapability.FileManagement.File.FileIO 4844 4845**返回值:** 4846 4847 | 类型 | 说明 | 4848 | ------- | --------------------- | 4849 | boolean | 表示文件是否是 FIFO。true:是FIFO;false:不是FIFO。 | 4850 4851**错误码:** 4852 4853接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4854 4855**示例:** 4856 4857 ```ts 4858 let filePath = pathDir + "/test.txt"; 4859 let isFIFO = fs.statSync(filePath).isFIFO(); 4860 ``` 4861 4862### isFile 4863 4864isFile(): boolean 4865 4866用于判断文件是否是普通文件。 4867 4868**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 4869 4870**系统能力**:SystemCapability.FileManagement.File.FileIO 4871 4872**返回值:** 4873 4874 | 类型 | 说明 | 4875 | ------- | --------------- | 4876 | boolean | 表示文件是否是普通文件。true:是普通文件;false:不是普通文件。 | 4877 4878**错误码:** 4879 4880接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4881 4882**示例:** 4883 4884 ```ts 4885 let filePath = pathDir + "/test.txt"; 4886 let isFile = fs.statSync(filePath).isFile(); 4887 ``` 4888 4889### isSocket 4890 4891isSocket(): boolean 4892 4893判断文件是否是套接字。 4894 4895**系统能力**:SystemCapability.FileManagement.File.FileIO 4896 4897**返回值:** 4898 4899 | 类型 | 说明 | 4900 | ------- | -------------- | 4901 | boolean | 表示文件是否是套接字。true:是套接字;false:不是套接字。 | 4902 4903**错误码:** 4904 4905接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4906 4907**示例:** 4908 4909 ```ts 4910 let filePath = pathDir + "/test.txt"; 4911 let isSocket = fs.statSync(filePath).isSocket(); 4912 ``` 4913 4914### isSymbolicLink 4915 4916isSymbolicLink(): boolean 4917 4918判断文件是否为符号链接。 4919 4920**系统能力**:SystemCapability.FileManagement.File.FileIO 4921 4922**返回值:** 4923 4924 | 类型 | 说明 | 4925 | ------- | --------------- | 4926 | boolean | 表示文件是否是符号链接。true:是符号链接;false:不是符号链接。 | 4927 4928**错误码:** 4929 4930接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4931 4932**示例:** 4933 4934 ```ts 4935 let filePath = pathDir + "/test.txt"; 4936 let isSymbolicLink = fs.statSync(filePath).isSymbolicLink(); 4937 ``` 4938 4939## Stream 4940 4941文件流,在调用Stream的方法前,需要先通过[fs.createStream](#fscreatestream)方法或者[fs.fdopenStream](#fsfdopenstream)(同步或异步)来构建一个Stream实例。 4942 4943### close 4944 4945close(): Promise<void> 4946 4947关闭文件流,使用promise异步回调。 4948 4949**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 4950 4951**系统能力**:SystemCapability.FileManagement.File.FileIO 4952 4953**返回值:** 4954 4955 | 类型 | 说明 | 4956 | ------------------- | ------------- | 4957 | Promise<void> | Promise对象。无返回值。 | 4958 4959**错误码:** 4960 4961接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4962 4963**示例:** 4964 4965 ```ts 4966 import { BusinessError } from '@kit.BasicServicesKit'; 4967 let filePath = pathDir + "/test.txt"; 4968 let stream = fs.createStreamSync(filePath, "r+"); 4969 stream.close().then(() => { 4970 console.info("close fileStream succeed"); 4971 }).catch((err: BusinessError) => { 4972 console.error("close fileStream failed with error message: " + err.message + ", error code: " + err.code); 4973 }); 4974 ``` 4975 4976### close 4977 4978close(callback: AsyncCallback<void>): void 4979 4980异步关闭文件流,使用callback异步回调。 4981 4982**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 4983 4984**系统能力**:SystemCapability.FileManagement.File.FileIO 4985 4986**参数:** 4987 4988 | 参数名 | 类型 | 必填 | 说明 | 4989 | -------- | ------------------------- | ---- | ------------- | 4990 | callback | AsyncCallback<void> | 是 | 异步关闭文件流之后的回调。 | 4991 4992**错误码:** 4993 4994接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4995 4996**示例:** 4997 4998 ```ts 4999 import { BusinessError } from '@kit.BasicServicesKit'; 5000 let filePath = pathDir + "/test.txt"; 5001 let stream = fs.createStreamSync(filePath, "r+"); 5002 stream.close((err: BusinessError) => { 5003 if (err) { 5004 console.error("close stream failed with error message: " + err.message + ", error code: " + err.code); 5005 } else { 5006 console.info("close stream succeed"); 5007 } 5008 }); 5009 ``` 5010 5011### closeSync 5012 5013closeSync(): void 5014 5015同步关闭文件流。 5016 5017**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 5018 5019**系统能力**:SystemCapability.FileManagement.File.FileIO 5020 5021**错误码:** 5022 5023接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5024 5025**示例:** 5026 5027 ```ts 5028 let filePath = pathDir + "/test.txt"; 5029 let stream = fs.createStreamSync(filePath, "r+"); 5030 stream.closeSync(); 5031 ``` 5032 5033### flush 5034 5035flush(): Promise<void> 5036 5037刷新文件流,使用promise异步回调。 5038 5039**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 5040 5041**系统能力**:SystemCapability.FileManagement.File.FileIO 5042 5043**返回值:** 5044 5045 | 类型 | 说明 | 5046 | ------------------- | ------------- | 5047 | Promise<void> | Promise对象。返回表示异步刷新文件流的结果。 | 5048 5049**错误码:** 5050 5051接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5052 5053**示例:** 5054 5055 ```ts 5056 import { BusinessError } from '@kit.BasicServicesKit'; 5057 let filePath = pathDir + "/test.txt"; 5058 let stream = fs.createStreamSync(filePath, "r+"); 5059 stream.flush().then(() => { 5060 console.info("flush succeed"); 5061 stream.close(); 5062 }).catch((err: BusinessError) => { 5063 console.error("flush failed with error message: " + err.message + ", error code: " + err.code); 5064 }); 5065 ``` 5066 5067### flush 5068 5069flush(callback: AsyncCallback<void>): void 5070 5071异步刷新文件流,使用callback异步回调。 5072 5073**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 5074 5075**系统能力**:SystemCapability.FileManagement.File.FileIO 5076 5077**参数:** 5078 5079 | 参数名 | 类型 | 必填 | 说明 | 5080 | -------- | ------------------------- | ---- | -------------- | 5081 | callback | AsyncCallback<void> | 是 | 异步刷新文件流后的回调函数。 | 5082 5083**错误码:** 5084 5085接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5086 5087**示例:** 5088 5089 ```ts 5090 import { BusinessError } from '@kit.BasicServicesKit'; 5091 let filePath = pathDir + "/test.txt"; 5092 let stream = fs.createStreamSync(filePath, "r+"); 5093 stream.flush((err: BusinessError) => { 5094 if (err) { 5095 console.error("flush stream failed with error message: " + err.message + ", error code: " + err.code); 5096 } else { 5097 console.info("flush succeed"); 5098 stream.close(); 5099 } 5100 }); 5101 ``` 5102 5103### flushSync 5104 5105flushSync(): void 5106 5107同步刷新文件流。 5108 5109**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 5110 5111**系统能力**:SystemCapability.FileManagement.File.FileIO 5112 5113**错误码:** 5114 5115接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5116 5117**示例:** 5118 5119 ```ts 5120 let filePath = pathDir + "/test.txt"; 5121 let stream = fs.createStreamSync(filePath, "r+"); 5122 stream.flushSync(); 5123 stream.close(); 5124 ``` 5125 5126### write 5127 5128write(buffer: ArrayBuffer | string, options?: WriteOptions): Promise<number> 5129 5130将数据写入流文件,使用promise异步回调。 5131 5132**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 5133 5134**系统能力**:SystemCapability.FileManagement.File.FileIO 5135 5136**参数:** 5137 5138 | 参数名 | 类型 | 必填 | 说明 | 5139 | ------- | ------------------------------- | ---- | ---------------------------------------- | 5140 | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | 5141 | options | [WriteOptions](#writeoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示期望写入数据的长度。默认缓冲区长度。<br/>- offset,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写。<br/>- encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 'utf-8'。仅支持 'utf-8'。| 5142 5143**返回值:** 5144 5145 | 类型 | 说明 | 5146 | --------------------- | -------- | 5147 | Promise<number> | Promise对象。返回实际写入的长度。 | 5148 5149**错误码:** 5150 5151接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5152 5153**示例:** 5154 5155 ```ts 5156 import { BusinessError } from '@kit.BasicServicesKit'; 5157 import { fileIo as fs, WriteOptions } from '@kit.CoreFileKit'; 5158 let filePath = pathDir + "/test.txt"; 5159 let stream = fs.createStreamSync(filePath, "r+"); 5160 let writeOption: WriteOptions = { 5161 offset: 5, 5162 length: 5, 5163 encoding: 'utf-8' 5164 }; 5165 stream.write("hello, world", writeOption).then((number: number) => { 5166 console.info("write succeed and size is:" + number); 5167 stream.close(); 5168 }).catch((err: BusinessError) => { 5169 console.error("write failed with error message: " + err.message + ", error code: " + err.code); 5170 }); 5171 ``` 5172 5173### write 5174 5175write(buffer: ArrayBuffer | string, options?: WriteOptions, callback: AsyncCallback<number>): void 5176 5177将数据写入流文件,使用callback异步回调。 5178 5179**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 5180 5181**系统能力**:SystemCapability.FileManagement.File.FileIO 5182 5183**参数:** 5184 5185 | 参数名 | 类型 | 必填 | 说明 | 5186 | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | 5187 | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | 5188 | options | [WriteOptions](#writeoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示期望写入数据的长度。可选,默认缓冲区长度。<br/>- offset,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写。<br/>- encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 'utf-8'。仅支持 'utf-8'。| 5189 | callback | AsyncCallback<number> | 是 | 异步写入完成后执行的回调函数。 | 5190 5191**错误码:** 5192 5193接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5194 5195**示例:** 5196 5197 ```ts 5198 import { BusinessError } from '@kit.BasicServicesKit'; 5199 import { fileIo as fs, WriteOptions } from '@kit.CoreFileKit'; 5200 let filePath = pathDir + "/test.txt"; 5201 let stream = fs.createStreamSync(filePath, "r+"); 5202 let writeOption: WriteOptions = { 5203 offset: 5, 5204 length: 5, 5205 encoding: 'utf-8' 5206 }; 5207 stream.write("hello, world", writeOption, (err: BusinessError, bytesWritten: number) => { 5208 if (err) { 5209 console.error("write stream failed with error message: " + err.message + ", error code: " + err.code); 5210 } else { 5211 if (bytesWritten) { 5212 console.info("write succeed and size is:" + bytesWritten); 5213 } 5214 } 5215 stream.close(); 5216 }); 5217 ``` 5218 5219### writeSync 5220 5221writeSync(buffer: ArrayBuffer | string, options?: WriteOptions): number 5222 5223以同步方法将数据写入流文件。 5224 5225**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 5226 5227**系统能力**:SystemCapability.FileManagement.File.FileIO 5228 5229**参数:** 5230 5231 | 参数名 | 类型 | 必填 | 说明 | 5232 | ------- | ------------------------------- | ---- | ---------------------------------------- | 5233 | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | 5234 | options | [WriteOptions](#writeoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示期望写入数据的长度。可选,默认缓冲区长度。<br/>- offset,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写。<br/>- encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 'utf-8'。仅支持 'utf-8'。| 5235 5236**返回值:** 5237 5238 | 类型 | 说明 | 5239 | ------ | -------- | 5240 | number | 实际写入的长度。 | 5241 5242**错误码:** 5243 5244接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5245 5246**示例:** 5247 5248 ```ts 5249 import { fileIo as fs, WriteOptions } from '@kit.CoreFileKit'; 5250 let filePath = pathDir + "/test.txt"; 5251 let stream = fs.createStreamSync(filePath,"r+"); 5252 let writeOption: WriteOptions = { 5253 offset: 5, 5254 length: 5, 5255 encoding: 'utf-8' 5256 }; 5257 let num = stream.writeSync("hello, world", writeOption); 5258 stream.close(); 5259 ``` 5260 5261### read 5262 5263read(buffer: ArrayBuffer, options?: ReadOptions): Promise<number> 5264 5265从流文件读取数据,使用promise异步回调。 5266 5267**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 5268 5269**系统能力**:SystemCapability.FileManagement.File.FileIO 5270 5271**参数:** 5272 5273 | 参数名 | 类型 | 必填 | 说明 | 5274 | ------- | ----------- | ---- | ---------------------------------------- | 5275 | buffer | ArrayBuffer | 是 | 用于读取文件的缓冲区。 | 5276 | options | [ReadOptions](#readoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示期望读取数据的长度。可选,默认缓冲区长度。<br/>- offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读。 | 5277 5278**返回值:** 5279 5280 | 类型 | 说明 | 5281 | ---------------------------------- | ------ | 5282 | Promise<number> | Promise对象。返回读取的结果。 | 5283 5284**错误码:** 5285 5286接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5287 5288**示例:** 5289 5290 ```ts 5291 import { BusinessError } from '@kit.BasicServicesKit'; 5292 import { buffer } from '@kit.ArkTS'; 5293 import { fileIo as fs, ReadOptions } from '@kit.CoreFileKit'; 5294 let filePath = pathDir + "/test.txt"; 5295 let stream = fs.createStreamSync(filePath, "r+"); 5296 let arrayBuffer = new ArrayBuffer(4096); 5297 let readOption: ReadOptions = { 5298 offset: 5, 5299 length: 5 5300 }; 5301 stream.read(arrayBuffer, readOption).then((readLen: number) => { 5302 console.info("read data succeed"); 5303 let buf = buffer.from(arrayBuffer, 0, readLen); 5304 console.info(`The content of file: ${buf.toString()}`); 5305 stream.close(); 5306 }).catch((err: BusinessError) => { 5307 console.error("read data failed with error message: " + err.message + ", error code: " + err.code); 5308 }); 5309 ``` 5310 5311### read 5312 5313read(buffer: ArrayBuffer, options?: ReadOptions, callback: AsyncCallback<number>): void 5314 5315从流文件读取数据,使用callback异步回调。 5316 5317**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 5318 5319**系统能力**:SystemCapability.FileManagement.File.FileIO 5320 5321**参数:** 5322 5323 | 参数名 | 类型 | 必填 | 说明 | 5324 | -------- | ---------------------------------------- | ---- | ---------------------------------------- | 5325 | buffer | ArrayBuffer | 是 | 用于读取文件的缓冲区。 | 5326 | options | [ReadOptions](#readoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示期望读取数据的长度。可选,默认缓冲区长度。<br/>- offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读取。| 5327 | callback | AsyncCallback<number> | 是 | 异步读取完成后的回调。 | 5328 5329**错误码:** 5330 5331接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5332 5333**示例:** 5334 5335 ```ts 5336 import { BusinessError } from '@kit.BasicServicesKit'; 5337 import { buffer } from '@kit.ArkTS'; 5338 import { fileIo as fs, ReadOptions } from '@kit.CoreFileKit'; 5339 let filePath = pathDir + "/test.txt"; 5340 let stream = fs.createStreamSync(filePath, "r+"); 5341 let arrayBuffer = new ArrayBuffer(4096); 5342 let readOption: ReadOptions = { 5343 offset: 5, 5344 length: 5 5345 }; 5346 stream.read(arrayBuffer, readOption, (err: BusinessError, readLen: number) => { 5347 if (err) { 5348 console.error("read stream failed with error message: " + err.message + ", error code: " + err.code); 5349 } else { 5350 console.info("read data succeed"); 5351 let buf = buffer.from(arrayBuffer, 0, readLen); 5352 console.info(`The content of file: ${buf.toString()}`); 5353 stream.close(); 5354 } 5355 }); 5356 ``` 5357 5358### readSync 5359 5360readSync(buffer: ArrayBuffer, options?: ReadOptions): number 5361 5362以同步方法从流文件读取数据。 5363 5364**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。 5365 5366**系统能力**:SystemCapability.FileManagement.File.FileIO 5367 5368**参数:** 5369 5370 | 参数名 | 类型 | 必填 | 说明 | 5371 | ------- | ----------- | ---- | ---------------------------------------- | 5372 | buffer | ArrayBuffer | 是 | 用于读取文件的缓冲区。 | 5373 | options | [ReadOptions](#readoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示期望读取数据的长度。可选,默认缓冲区长度。<br/>- offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读。<br/> | 5374 5375**返回值:** 5376 5377 | 类型 | 说明 | 5378 | ------ | -------- | 5379 | number | 实际读取的长度。 | 5380 5381**错误码:** 5382 5383接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5384 5385**示例:** 5386 5387 ```ts 5388 import { fileIo as fs, ReadOptions } from '@kit.CoreFileKit'; 5389 let filePath = pathDir + "/test.txt"; 5390 let stream = fs.createStreamSync(filePath, "r+"); 5391 let readOption: ReadOptions = { 5392 offset: 5, 5393 length: 5 5394 }; 5395 let buf = new ArrayBuffer(4096); 5396 let num = stream.readSync(buf, readOption); 5397 stream.close(); 5398 ``` 5399 5400## File 5401 5402由open接口打开的File对象。 5403 5404**系统能力**:SystemCapability.FileManagement.File.FileIO 5405 5406### 属性 5407 5408| 名称 | 类型 | 只读 | 可选 | 说明 | 5409| ---- | ------ | ---- | ---- | ------- | 5410| fd | number | 是 | 否 | 打开的文件描述符。<br>**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 | 5411| path<sup>10+</sup> | string | 是 | 否 | 文件路径。 | 5412| name<sup>10+</sup> | string | 是 | 否 | 文件名。 | 5413 5414### getParent<sup>11+</sup> 5415 5416getParent(): string 5417 5418获取File对象对应文件父目录。 5419 5420**系统能力**:SystemCapability.FileManagement.File.FileIO 5421 5422**返回值:** 5423 5424 | 类型 | 说明 | 5425 | ---------------------------------- | ------ | 5426 | string | 返回父目录路径。 | 5427 5428**错误码:** 5429 5430接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5431 5432**示例:** 5433 5434 ```ts 5435 import { BusinessError } from '@kit.BasicServicesKit'; 5436 let filePath = pathDir + "/test.txt"; 5437 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 5438 console.info('The parent path is: ' + file.getParent()); 5439 fs.closeSync(file); 5440 ``` 5441 5442### lock 5443 5444lock(exclusive?: boolean): Promise\<void> 5445 5446对文件阻塞式施加共享锁或独占锁,使用promise异步回调。 5447 5448**系统能力**:SystemCapability.FileManagement.File.FileIO 5449 5450**参数:** 5451 5452 | 参数名 | 类型 | 必填 | 说明 | 5453 | ------- | ----------- | ---- | ---------------------------------------- | 5454 | exclusive | boolean | 否 | 是否施加独占锁,默认false。true:施加独占锁;false:不施加独占锁。 | 5455 5456**返回值:** 5457 5458 | 类型 | 说明 | 5459 | ---------------------------------- | ------ | 5460 | Promise<void> | Promise对象。无返回值。 | 5461 5462**错误码:** 5463 5464接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5465 5466**示例:** 5467 5468 ```ts 5469 import { BusinessError } from '@kit.BasicServicesKit'; 5470 let filePath = pathDir + "/test.txt"; 5471 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 5472 file.lock(true).then(() => { 5473 console.info("lock file succeed"); 5474 }).catch((err: BusinessError) => { 5475 console.error("lock file failed with error message: " + err.message + ", error code: " + err.code); 5476 }).finally(() => { 5477 fs.closeSync(file); 5478 }); 5479 ``` 5480 5481### lock 5482 5483lock(exclusive?: boolean, callback: AsyncCallback\<void>): void 5484 5485对文件阻塞式施加共享锁或独占锁,使Callback异步回调。 5486 5487**系统能力**:SystemCapability.FileManagement.File.FileIO 5488 5489**参数:** 5490 5491 | 参数名 | 类型 | 必填 | 说明 | 5492 | ------- | ----------- | ---- | ---------------------------------------- | 5493 | exclusive | boolean | 否 | 是否施加独占锁,默认false。true:施加独占锁;false:不施加独占锁。 | 5494 | callback | AsyncCallback<void> | 是 | 异步文件上锁之后的回调。 | 5495 5496**错误码:** 5497 5498接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5499 5500**示例:** 5501 5502 ```ts 5503 import { BusinessError } from '@kit.BasicServicesKit'; 5504 let filePath = pathDir + "/test.txt"; 5505 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 5506 file.lock(true, (err: BusinessError) => { 5507 if (err) { 5508 console.error("lock file failed with error message: " + err.message + ", error code: " + err.code); 5509 } else { 5510 console.info("lock file succeed"); 5511 } 5512 fs.closeSync(file); 5513 }); 5514 ``` 5515 5516### tryLock 5517 5518tryLock(exclusive?: boolean): void 5519 5520文件非阻塞式施加共享锁或独占锁。 5521 5522**系统能力**:SystemCapability.FileManagement.File.FileIO 5523 5524**参数:** 5525 5526 | 参数名 | 类型 | 必填 | 说明 | 5527 | ------- | ----------- | ---- | ---------------------------------------- | 5528 | exclusive | boolean | 否 | 是否施加独占锁,默认false。true:施加独占锁;false:不施加独占锁。 | 5529 5530**错误码:** 5531 5532接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5533 5534**示例:** 5535 5536 ```ts 5537 let filePath = pathDir + "/test.txt"; 5538 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 5539 file.tryLock(true); 5540 console.info("lock file succeed"); 5541 fs.closeSync(file); 5542 ``` 5543 5544### unlock 5545 5546unlock(): void 5547 5548以同步方式解锁文件。 5549 5550**系统能力**:SystemCapability.FileManagement.File.FileIO 5551 5552**错误码:** 5553 5554接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5555 5556**示例:** 5557 5558 ```ts 5559 let filePath = pathDir + "/test.txt"; 5560 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 5561 file.tryLock(true); 5562 file.unlock(); 5563 console.info("unlock file succeed"); 5564 fs.closeSync(file); 5565 ``` 5566 5567 ## fs.DfsListeners<sup>12+</sup> 5568 5569interface DfsListeners { 5570 onStatus(networkId: string, status: number): void 5571} 5572 5573事件监听类。创建DFSListener对象,用于监听分布式文件系统状态。 5574 5575**系统能力**:SystemCapability.FileManagement.File.FileIO 5576 5577### onStatus<sup>12+</sup> 5578 5579onStatus(networkId: string, status: number): void; 5580 5581事件回调类。参数由[connectDfs](#fsconnectdfs12)传入。 5582 5583**系统能力**:SystemCapability.FileManagement.File.FileIO 5584 5585**参数:** 5586 5587 | 参数名 | 类型 | 必填 | 说明 | 5588 | ---- | ------ | ---- | ---------------------------------------- | 5589 | networkId | string | 是 | 设备的网络Id。 | 5590 | status | number | 是 | 分布式文件系统的状态码(以connectDfs回调onStatus的特定错误码作为入参)。触发场景为connectDfs调用过程中出现对端设备异常,对应错误码为:<br/>- [13900046](errorcode-filemanagement.md#13900046-软件造成连接中断):软件造成连接中断。 5591 5592## RandomAccessFile 5593 5594随机读写文件流。在调用RandomAccessFile的方法前,需要先通过createRandomAccessFile()方法(同步或异步)来构建一个RandomAccessFile实例。 5595 5596**系统能力**:SystemCapability.FileManagement.File.FileIO 5597 5598### 属性 5599 5600| 名称 | 类型 | 只读 | 可选 | 说明 | 5601| ----------- | ------ | ---- | ----- | ---------------- | 5602| fd | number | 是 | 否 | 打开的文件描述符。 | 5603| filePointer | number | 是 | 否 | RandomAccessFile对象的偏移指针。 | 5604 5605### setFilePointer<sup>10+</sup> 5606 5607setFilePointer(filePointer:number): void 5608 5609设置文件偏移指针。 5610 5611**系统能力**:SystemCapability.FileManagement.File.FileIO 5612 5613**参数:** 5614 5615 | 参数名 | 类型 | 必填 | 说明 | 5616 | ------- | ----------- | ---- | ----------------------------- | 5617 | filePointer | number | 是 | RandomAccessFile对象的偏移指针。 | 5618 5619**错误码:** 5620 5621接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5622 5623**示例:** 5624 5625 ```ts 5626 let filePath = pathDir + "/test.txt"; 5627 let randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 5628 randomAccessFile.setFilePointer(1); 5629 randomAccessFile.close(); 5630 ``` 5631 5632 5633### close<sup>10+</sup> 5634 5635close(): void 5636 5637以同步方式关闭RandomAccessFile对象。 5638 5639**系统能力**:SystemCapability.FileManagement.File.FileIO 5640 5641**错误码:** 5642 5643接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5644 5645**示例:** 5646 5647 ```ts 5648 let filePath = pathDir + "/test.txt"; 5649 let randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 5650 randomAccessFile.close(); 5651 ``` 5652 5653### write<sup>10+</sup> 5654 5655write(buffer: ArrayBuffer | string, options?: WriteOptions): Promise<number> 5656 5657将数据写入文件,使用promise异步回调。 5658 5659**系统能力**:SystemCapability.FileManagement.File.FileIO 5660 5661**参数:** 5662 5663 | 参数名 | 类型 | 必填 | 说明 | 5664 | ------- | ------------------------------- | ---- | ---------------------------------------- | 5665 | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | 5666 | options | [WriteOptions](#writeoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示期望写入数据的长度。默认缓冲区长度。<br/>- offset,number类型,表示期望写入文件位置(基于当前filePointer加上offset的位置)。可选,默认从偏移指针(filePointer)开始写。<br/>- encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 'utf-8'。仅支持 'utf-8'。| 5667 5668**返回值:** 5669 5670 | 类型 | 说明 | 5671 | --------------------- | -------- | 5672 | Promise<number> | Promise对象。返回实际写入的长度。 | 5673 5674**错误码:** 5675 5676接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5677 5678**示例:** 5679 5680 ```ts 5681 import { BusinessError } from '@kit.BasicServicesKit'; 5682 import { fileIo as fs, WriteOptions } from '@kit.CoreFileKit'; 5683 let filePath = pathDir + "/test.txt"; 5684 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 5685 let randomAccessFile = fs.createRandomAccessFileSync(file); 5686 let bufferLength: number = 4096; 5687 let writeOption: WriteOptions = { 5688 offset: 1, 5689 length: 5, 5690 encoding: 'utf-8' 5691 }; 5692 let arrayBuffer = new ArrayBuffer(bufferLength); 5693 randomAccessFile.write(arrayBuffer, writeOption).then((bytesWritten: number) => { 5694 console.info("randomAccessFile bytesWritten: " + bytesWritten); 5695 }).catch((err: BusinessError) => { 5696 console.error("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code); 5697 }).finally(() => { 5698 randomAccessFile.close(); 5699 fs.closeSync(file); 5700 }); 5701 5702 ``` 5703 5704### write<sup>10+</sup> 5705 5706write(buffer: ArrayBuffer | string, options?: WriteOptions, callback: AsyncCallback<number>): void 5707 5708将数据写入文件,使用callback异步回调。 5709 5710**系统能力**:SystemCapability.FileManagement.File.FileIO 5711 5712**参数:** 5713 5714 | 参数名 | 类型 | 必填 | 说明 | 5715 | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | 5716 | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | 5717 | options | [WriteOptions](#writeoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示期望写入数据的长度。可选,默认为缓冲区长度。<br/>- offset,number类型,表示期望写入文件位置(基于当前filePointer加上offset的位置)。可选,默认从偏移指针(filePointer)开始写。<br/>- encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 'utf-8'。仅支持 'utf-8'。| 5718 | callback | AsyncCallback<number> | 是 | 异步写入完成后执行的回调函数。 | 5719 5720**错误码:** 5721 5722接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5723 5724**示例:** 5725 5726 ```ts 5727 import { BusinessError } from '@kit.BasicServicesKit'; 5728 import { fileIo as fs, WriteOptions } from '@kit.CoreFileKit'; 5729 let filePath = pathDir + "/test.txt"; 5730 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 5731 let randomAccessFile = fs.createRandomAccessFileSync(file); 5732 let bufferLength: number = 4096; 5733 let writeOption: WriteOptions = { 5734 offset: 1, 5735 length: bufferLength, 5736 encoding: 'utf-8' 5737 }; 5738 let arrayBuffer = new ArrayBuffer(bufferLength); 5739 randomAccessFile.write(arrayBuffer, writeOption, (err: BusinessError, bytesWritten: number) => { 5740 if (err) { 5741 console.error("write failed with error message: " + err.message + ", error code: " + err.code); 5742 } else { 5743 if (bytesWritten) { 5744 console.info("write succeed and size is:" + bytesWritten); 5745 } 5746 } 5747 randomAccessFile.close(); 5748 fs.closeSync(file); 5749 }); 5750 ``` 5751 5752### writeSync<sup>10+</sup> 5753 5754writeSync(buffer: ArrayBuffer | string, options?: WriteOptions): number 5755 5756以同步方法将数据写入文件。 5757 5758**系统能力**:SystemCapability.FileManagement.File.FileIO 5759 5760**参数:** 5761 5762 | 参数名 | 类型 | 必填 | 说明 | 5763 | ------- | ------------------------------- | ---- | ---------------------------------------- | 5764 | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | 5765 | options | [WriteOptions](#writeoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示期望写入数据的长度。可选,默认缓冲区长度。<br/>- offset,number类型,表示期望写入文件位置(基于当前filePointer加上offset的位置)。可选,默认从偏移指针(filePointer)开始写。<br/>- encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 'utf-8'。仅支持 'utf-8'。| 5766 5767**返回值:** 5768 5769 | 类型 | 说明 | 5770 | ------ | -------- | 5771 | number | 实际写入的长度。 | 5772 5773**错误码:** 5774 5775接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5776 5777**示例:** 5778 5779 ```ts 5780 import { fileIo as fs, WriteOptions } from '@kit.CoreFileKit'; 5781 let filePath = pathDir + "/test.txt"; 5782 let randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 5783 let writeOption: WriteOptions = { 5784 offset: 5, 5785 length: 5, 5786 encoding: 'utf-8' 5787 }; 5788 let bytesWritten = randomAccessFile.writeSync("hello, world", writeOption); 5789 randomAccessFile.close(); 5790 ``` 5791 5792### read<sup>10+</sup> 5793 5794read(buffer: ArrayBuffer, options?: ReadOptions): Promise<number> 5795 5796从文件读取数据,使用promise异步回调。 5797 5798**系统能力**:SystemCapability.FileManagement.File.FileIO 5799 5800**参数:** 5801 5802 | 参数名 | 类型 | 必填 | 说明 | 5803 | ------- | ----------- | ---- | ---------------------------------------- | 5804 | buffer | ArrayBuffer | 是 | 用于读取文件的缓冲区。 | 5805 | options | [ReadOptions](#readoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示期望读取数据的长度。可选,默认为缓冲区长度。<br/>- offset,number类型,表示期望读取文件位置(基于当前filePointer加上offset的位置)。可选,默认从偏移指针(filePointer)开始读。 | 5806 5807**返回值:** 5808 5809 | 类型 | 说明 | 5810 | ---------------------------------- | ------ | 5811 | Promise<number> | Promise对象。返回读取的结果。 | 5812 5813**错误码:** 5814 5815接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5816 5817**示例:** 5818 5819 ```ts 5820 import { BusinessError } from '@kit.BasicServicesKit'; 5821 import { fileIo as fs, ReadOptions } from '@kit.CoreFileKit'; 5822 let filePath = pathDir + "/test.txt"; 5823 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 5824 let randomAccessFile = fs.createRandomAccessFileSync(file); 5825 let bufferLength: number = 4096; 5826 let readOption: ReadOptions = { 5827 offset: 1, 5828 length: 5 5829 }; 5830 let arrayBuffer = new ArrayBuffer(bufferLength); 5831 randomAccessFile.read(arrayBuffer, readOption).then((readLength: number) => { 5832 console.info("randomAccessFile readLength: " + readLength); 5833 }).catch((err: BusinessError) => { 5834 console.error("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code); 5835 }).finally(() => { 5836 randomAccessFile.close(); 5837 fs.closeSync(file); 5838 }); 5839 ``` 5840 5841### read<sup>10+</sup> 5842 5843read(buffer: ArrayBuffer, options?: ReadOptions, callback: AsyncCallback<number>): void 5844 5845从文件读取数据,使用callback异步回调。 5846 5847**系统能力**:SystemCapability.FileManagement.File.FileIO 5848 5849**参数:** 5850 5851 | 参数名 | 类型 | 必填 | 说明 | 5852 | -------- | ---------------------------------------- | ---- | ---------------------------------------- | 5853 | buffer | ArrayBuffer | 是 | 用于读取文件的缓冲区。 | 5854 | options | [ReadOptions](#readoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示读取数据的长度。可选,默认为缓冲区长度。<br/>- offset,number类型,表示读取文件位置(基于当前filePointer加上offset的位置)。可选,默认从filePointer开始读。 | 5855 | callback | AsyncCallback<number> | 是 | 异步读取完成后的回调。 | 5856 5857**错误码:** 5858 5859接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5860 5861**示例:** 5862 5863 ```ts 5864 import { BusinessError } from '@kit.BasicServicesKit'; 5865 import { fileIo as fs, ReadOptions } from '@kit.CoreFileKit'; 5866 let filePath = pathDir + "/test.txt"; 5867 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 5868 let randomAccessFile = fs.createRandomAccessFileSync(file); 5869 let length: number = 20; 5870 let readOption: ReadOptions = { 5871 offset: 1, 5872 length: 5 5873 }; 5874 let arrayBuffer = new ArrayBuffer(length); 5875 randomAccessFile.read(arrayBuffer, readOption, (err: BusinessError, readLength: number) => { 5876 if (err) { 5877 console.error("read failed with error message: " + err.message + ", error code: " + err.code); 5878 } else { 5879 if (readLength) { 5880 console.info("read succeed and size is:" + readLength); 5881 } 5882 } 5883 randomAccessFile.close(); 5884 fs.closeSync(file); 5885 }); 5886 ``` 5887 5888### readSync<sup>10+</sup> 5889 5890readSync(buffer: ArrayBuffer, options?: ReadOptions): number 5891 5892以同步方法从文件读取数据。 5893 5894**系统能力**:SystemCapability.FileManagement.File.FileIO 5895 5896**参数:** 5897 5898 | 参数名 | 类型 | 必填 | 说明 | 5899 | ------- | ----------- | ---- | ---------------------------------------- | 5900 | buffer | ArrayBuffer | 是 | 用于读取文件的缓冲区。 | 5901 | options | [ReadOptions](#readoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示期望读取数据的长度。可选,默认缓冲区长度。<br/>- offset,number类型,表示期望读取文件位置(基于当前filePointer加上offset的位置)。可选,默认从偏移指针(filePointer)开始读。<br/> | 5902 5903**返回值:** 5904 5905 | 类型 | 说明 | 5906 | ------ | -------- | 5907 | number | 实际读取的长度。 | 5908 5909**错误码:** 5910 5911接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5912 5913**示例:** 5914 5915 ```ts 5916 let filePath = pathDir + "/test.txt"; 5917 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 5918 let randomAccessFile = fs.createRandomAccessFileSync(file); 5919 let length: number = 4096; 5920 let arrayBuffer = new ArrayBuffer(length); 5921 let readLength = randomAccessFile.readSync(arrayBuffer); 5922 randomAccessFile.close(); 5923 fs.closeSync(file); 5924 ``` 5925 5926### getReadStream<sup>12+</sup> 5927 5928getReadStream(): ReadStream 5929 5930获取当前 RandomAccessFile 的一个 ReadStream 实例。 5931 5932**系统能力**:SystemCapability.FileManagement.File.FileIO 5933 5934**返回值:** 5935 5936 | 类型 | 说明 | 5937 | ------------------ | --------- | 5938 | [ReadStream](#readstream12) | 文件可读流。 | 5939 5940**示例:** 5941 5942 ```ts 5943 const filePath = pathDir + "/test.txt"; 5944 const randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 5945 const rs = randomAccessFile.getReadStream(); 5946 rs.close(); 5947 randomAccessFile.close(); 5948 ``` 5949 5950### getWriteStream<sup>12+</sup> 5951 5952getWriteStream(): WriteStream 5953 5954获取当前 RandomAccessFile 的一个 WriteStream 实例。 5955 5956**系统能力**:SystemCapability.FileManagement.File.FileIO 5957 5958**返回值:** 5959 5960 | 类型 | 说明 | 5961 | ------------------ | --------- | 5962 | [WriteStream](#writestream12) | 文件可写流。 | 5963 5964**示例:** 5965 5966 ```ts 5967 const filePath = pathDir + "/test.txt"; 5968 const randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 5969 const ws = randomAccessFile.getWriteStream(); 5970 ws.close(); 5971 randomAccessFile.close(); 5972 ``` 5973 5974 5975## Watcher<sup>10+</sup> 5976 5977文件目录变化监听对象。由createWatcher接口获得。 5978 5979### start<sup>10+</sup> 5980 5981start(): void 5982 5983开启监听。 5984 5985**系统能力**:SystemCapability.FileManagement.File.FileIO 5986 5987**错误码:** 5988 5989接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5990 5991**示例:** 5992 5993 ```ts 5994 let filePath = pathDir + "/test.txt"; 5995 let watcher = fs.createWatcher(filePath, 0xfff, () => {}); 5996 watcher.start(); 5997 watcher.stop(); 5998 ``` 5999 6000### stop<sup>10+</sup> 6001 6002stop(): void 6003 6004停止监听并移除Watcher对象。 6005 6006**系统能力**:SystemCapability.FileManagement.File.FileIO 6007 6008**错误码:** 6009 6010接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 6011 6012**示例:** 6013 6014 ```ts 6015 let filePath = pathDir + "/test.txt"; 6016 let watcher = fs.createWatcher(filePath, 0xfff, () => {}); 6017 watcher.start(); 6018 watcher.stop(); 6019 ``` 6020 6021## OpenMode 6022 6023open接口flags参数常量。文件打开标签。 6024 6025**系统能力**:SystemCapability.FileManagement.File.FileIO 6026 6027| 名称 | 类型 | 值 | 说明 | 6028| ---- | ------ |---- | ------- | 6029| READ_ONLY | number | 0o0 | 只读打开。<br>**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 | 6030| WRITE_ONLY | number | 0o1 | 只写打开。<br>**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 | 6031| READ_WRITE | number | 0o2 | 读写打开。<br>**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 | 6032| CREATE | number | 0o100 | 若文件不存在,则创建文件。<br>**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 | 6033| TRUNC | number | 0o1000 | 如果文件存在且以只写或读写的方式打开,则将其长度裁剪为零。<br>**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 | 6034| APPEND | number | 0o2000 | 以追加方式打开,后续写将追加到文件末尾。<br>**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 | 6035| NONBLOCK | number | 0o4000 | 如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。 | 6036| DIR | number | 0o200000 | 如果path不指向目录,则出错。 | 6037| NOFOLLOW | number | 0o400000 | 如果path指向符号链接,则出错。 | 6038| SYNC | number | 0o4010000 | 以同步IO的方式打开文件。 | 6039 6040## Filter<sup>10+</sup> 6041 6042文件过滤配置项,支持listFile接口使用。 6043 6044**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 6045 6046**系统能力**:SystemCapability.FileManagement.File.FileIO 6047 6048| 名称 | 类型 | 必选 | 说明 | 6049| ----------- | --------------- | ------------------ | ------------------ | 6050| suffix | Array<string> | 否 | 文件后缀名完全匹配,各个关键词OR关系。 | 6051| displayName | Array<string> | 否 | 文件名模糊匹配,各个关键词OR关系。当前仅支持通配符*。 | 6052| mimeType | Array<string> | 否 | mime类型完全匹配,各个关键词OR关系。预留字段,暂不支持使用。 | 6053| fileSizeOver | number | 否 | 文件大小匹配,大于指定大小的文件。 | 6054| lastModifiedAfter | number | 否 | 文件最近修改时间匹配,在指定时间点及之后的文件。 | 6055| excludeMedia | boolean | 否 | 是否排除Media中已有的文件。true:排除Media中已有的文件;false:不排除Media中已有的文件。 | 6056 6057## ConflictFiles<sup>10+</sup> 6058 6059冲突文件信息,支持copyDir及moveDir接口使用。 6060 6061**系统能力**:SystemCapability.FileManagement.File.FileIO 6062 6063| 名称 | 类型 | 说明 | 6064| ----------- | --------------- | ------------------ | 6065| srcFile | string | 源冲突文件路径。 | 6066| destFile | string | 目标冲突文件路径。 | 6067 6068## Options<sup>11+</sup> 6069 6070可选项类型,支持readLines接口使用。 6071 6072**系统能力**:SystemCapability.FileManagement.File.FileIO 6073 6074| 名称 | 类型 | 说明 | 6075| ----------- | --------------- | ------------------ | 6076| encoding | string | 文件编码方式。可选项。 | 6077 6078## WhenceType<sup>11+</sup> 6079 6080枚举,文件偏移指针相对偏移位置类型,支持lseek接口使用。 6081 6082**系统能力**:SystemCapability.FileManagement.File.FileIO 6083 6084| 名称 | 值 | 说明 | 6085| ----------- | --------------- | ------------------ | 6086| SEEK_SET | 0 | 文件起始位置处。 | 6087| SEEK_CUR | 1 | 当前文件偏移指针位置处。 | 6088| SEEK_END | 2 | 文件末尾位置处。 | 6089 6090## LocationType<sup>11+</sup> 6091 6092枚举,文件位置,表示该文件是否在本地或者云端存在。 6093 6094**系统能力**:SystemCapability.FileManagement.File.FileIO 6095 6096| 名称 | 值 | 说明 | 6097| ----------- | --------------- | ------------------ | 6098| LOCAL | 1 | 文件在本地存在。 | 6099| CLOUD | 2 | 文件在云端存在。 | 6100 6101## AccessModeType<sup>12+</sup> 6102 6103枚举,表示需要校验的具体权限。若不填,默认校验文件是否存在。 6104 6105**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 6106 6107**系统能力**:SystemCapability.FileManagement.File.FileIO 6108 6109| 名称 | 值 | 说明 | 6110| ----------- | --------------- | ------------------ | 6111| EXIST | 0 | 文件是否存在。 | 6112| WRITE | 2 | 文件是否具有写入权限。 | 6113| READ | 4 | 文件是否具有读取权限。 | 6114| READ_WRITE | 6 | 文件是否具有读写权限。 | 6115 6116## AccessFlagType<sup>12+</sup> 6117 6118枚举,表示需要校验的文件位置。 6119 6120**系统能力**:SystemCapability.FileManagement.File.FileIO 6121 6122| 名称 | 值 | 说明 | 6123| ----------- | --------------- | ------------------ | 6124| LOCAL | 0 | 文件是否在本地。 | 6125 6126## ReadOptions<sup>11+</sup> 6127 6128可选项类型,支持read接口使用。 6129 6130**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 6131 6132**系统能力**:SystemCapability.FileManagement.File.FileIO 6133 6134| 名称 | 类型 | 必选 | 说明 | 6135| ----------- | --------------- | ------------------ |------------------ | 6136| length | number | 否 | 期望读取数据的长度,单位为字节。可选,默认缓冲区长度。 | 6137| offset | number | 否 | 期望读取文件位置,单位为字节(基于当前filePointer加上offset的位置)。可选,默认从偏移指针(filePointer)开始读。 | 6138 6139## ReadTextOptions<sup>11+</sup> 6140 6141可选项类型,支持readText接口使用,ReadTextOptions继承至[ReadOptions](#readoptions11)。 6142 6143**系统能力**:SystemCapability.FileManagement.File.FileIO 6144 6145| 名称 | 类型 | 必选 | 说明 | 6146| ----------- | --------------- | ------------------ | ------------------ | 6147| length | number | 否 | 期望读取数据的长度,单位为字节。可选,默认文件长度。 | 6148| offset | number | 否 | 期望读取文件的位置,单位为字节。可选,默认从当前位置开始读取。 | 6149| encoding | string | 否 | 当数据是 string 类型时有效,表示数据的编码方式,默认 'utf-8',仅支持 'utf-8'。 <br>**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 | 6150 6151## WriteOptions<sup>11+</sup> 6152 6153可选项类型,支持write接口使用,WriteOptions继承至[Options](#options11)。 6154 6155**系统能力**:SystemCapability.FileManagement.File.FileIO 6156 6157| 名称 | 类型 | 必选 | 说明 | 6158| ----------- | --------------- | ------------------ | ------------------ | 6159| length | number | 否 | 期望写入数据的长度,单位为字节。可选,默认缓冲区长度。<br>**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 | 6160| offset | number | 否 | 期望写入文件位置,单位为字节(基于当前filePointer加上offset的位置)。可选,默认从偏移指针(filePointer)开始写。<br>**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 | 6161| encoding | string | 否 | 当数据是string类型时有效,表示数据的编码方式。默认 'utf-8'。仅支持 'utf-8'。 | 6162 6163## ListFileOptions<sup>11+</sup> 6164 6165可选项类型,支持listFile接口使用。 6166 6167**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 6168 6169**系统能力**:SystemCapability.FileManagement.File.FileIO 6170 6171| 名称 | 类型 | 必选 | 说明 | 6172| ----------- | --------------- | ------------------ | ------------------ | 6173| recursion | boolean | 否 | 是否递归子目录下文件名。可选,默认为false。当recursion为false时,返回当前目录下满足过滤要求的文件名及目录名。当recursion为true时,返回此目录下所有满足过滤要求的文件的相对路径(以/开头)。 | 6174| listNum | number | 否 | 列出文件名数量。可选,当设置0时,列出所有文件,默认为0。 | 6175| filter | [Filter](#filter10) | 否 | 文件过滤配置项。 可选,设置过滤条件。 | 6176 6177## ReadStream<sup>12+</sup> 6178 6179文件可读流,需要先通过[fs.createReadStream](#fscreatereadstream12)方法来构建一个ReadStream实例。ReadStream继承自数据流基类[stream](../apis-arkts/js-apis-stream.md#readable)。 6180 6181**规格**:ReadStream读到的数据为解码后的字符串,其编码格式当前仅支持'utf-8'。 6182 6183### 属性 6184 6185| 名称 | 类型 | 只读 | 可选 | 说明 | 6186| ------ | ------ | ---- | ---- | ---------------------------------------- | 6187| bytesRead | number | 是 | 否 | 可读流已经读取的字节数。 | 6188| path | string | 是 | 否 | 当前可读流对应的文件路径。 | 6189 6190### Seek 6191 6192seek(offset: number, whence?: WhenceType): number 6193 6194 6195调整可读流偏移指针位置。 6196 6197**系统能力**:SystemCapability.FileManagement.File.FileIO 6198 6199**参数:** 6200 6201 | 参数名 | 类型 | 必填 | 说明 | 6202 | ------ | ------ | ---- | --------------------------- | 6203 | offset | number | 是 | 相对偏移位置,单位为字节。 | 6204 | whence | [WhenceType](#whencetype11) | 否 | 偏移指针相对位置类型。默认值:SEEK_SET,文件起始位置处。 | 6205 6206**返回值:** 6207 6208 | 类型 | 说明 | 6209 | --------------------- | ---------- | 6210 | number | 当前可读流偏移指针位置(相对于文件头的偏移量,单位为字节)。 | 6211 6212**错误码:** 6213 6214接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 6215 6216**示例:** 6217 6218 ```ts 6219 const filePath = pathDir + "/test.txt"; 6220 const rs = fs.createReadStream(filePath); 6221 const curOff = rs.seek(5, fs.WhenceType.SEEK_SET); 6222 console.info(`current offset is ${curOff}`); 6223 rs.close(); 6224 ``` 6225 6226### close 6227 6228close(): void 6229 6230关闭可读流。 6231 6232**系统能力**:SystemCapability.FileManagement.File.FileIO 6233 6234**错误码:** 6235 6236接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 6237 6238**示例:** 6239 6240 ```ts 6241 const filePath = pathDir + "/test.txt"; 6242 const rs = fs.createReadStream(filePath); 6243 rs.close(); 6244 ``` 6245 6246## WriteStream<sup>12+</sup> 6247 6248文件可写流,需要先通过[fs.createWriteStream](#fscreatewritestream12)方法来构建一个WriteStream实例。WriteStream继承自数据流基类[stream](../apis-arkts/js-apis-stream.md#writable)。 6249 6250### 属性 6251 6252| 名称 | 类型 | 只读 | 可选 | 说明 | 6253| ------ | ------ | ---- | ---- | ---------------------------------------- | 6254| bytesWritten | number | 是 | 否 | 可写流已经写入的字节数。 | 6255| path | string | 是 | 否 | 当前可写流对应的文件路径。 | 6256 6257### Seek 6258 6259seek(offset: number, whence?: WhenceType): number; 6260 6261调整可写流的偏移指针位置。 6262 6263**系统能力**:SystemCapability.FileManagement.File.FileIO 6264 6265**参数:** 6266 6267 | 参数名 | 类型 | 必填 | 说明 | 6268 | ------ | ------ | ---- | --------------------------- | 6269 | offset | number | 是 | 相对偏移位置,单位为字节。 | 6270 | whence | [WhenceType](#whencetype11) | 否 | 偏移指针相对位置类型。默认值:SEEK_SET,文件起始位置处。 | 6271 6272**返回值:** 6273 6274 | 类型 | 说明 | 6275 | --------------------- | ---------- | 6276 | number | 当前可写流偏移指针位置(相对于文件头的偏移量,单位为字节)。 | 6277 6278**错误码:** 6279 6280接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 6281 6282**示例:** 6283 6284 ```ts 6285 const filePath = pathDir + "/test.txt"; 6286 const ws = fs.createWriteStream(filePath); 6287 const curOff = ws.seek(5, fs.WhenceType.SEEK_SET); 6288 console.info(`current offset is ${curOff}`); 6289 ws.close(); 6290 ``` 6291 6292### close 6293 6294close(): void 6295 6296关闭可写流。 6297 6298**系统能力**:SystemCapability.FileManagement.File.FileIO 6299 6300**错误码:** 6301 6302接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 6303 6304**示例:** 6305 6306 ```ts 6307 const filePath = pathDir + "/test.txt"; 6308 const ws = fs.createWriteStream(filePath); 6309 ws.close(); 6310 ``` 6311 6312## RandomAccessFileOptions<sup>12+</sup> 6313 6314可选项类型,支持 createRandomAccessFile 接口使用。 6315 6316**系统能力**:SystemCapability.FileManagement.File.FileIO 6317 6318| 名称 | 类型 | 必选 | 说明 | 6319| ----------- | --------------- | ------------------ | ------------------ | 6320| start | number | 否 | 表示期望读取文件的位置,单位为字节。可选,默认从当前位置开始读。 | 6321| end | number | 否 | 表示期望读取结束的位置,单位为字节。可选,默认文件末尾。 | 6322 6323## ReadStreamOptions<sup>12+</sup> 6324 6325可选项类型,支持 createReadStream 接口使用。 6326 6327**系统能力**:SystemCapability.FileManagement.File.FileIO 6328 6329| 名称 | 类型 | 必选 | 说明 | 6330| ----------- | --------------- | ------------------ | ------------------ | 6331| start | number | 否 | 表示期望读取文件的位置,单位为字节。可选,默认从当前位置开始读。 | 6332| end | number | 否 | 表示期望读取结束的位置,单位为字节。可选,默认文件末尾。 | 6333 6334## WriteStreamOptions<sup>12+</sup> 6335 6336可选项类型,支持 createWriteStream 接口使用。 6337 6338**系统能力**:SystemCapability.FileManagement.File.FileIO 6339 6340| 名称 | 类型 | 必选 | 说明 | 6341| ----------- | --------------- | ------------------ | ------------------ | 6342| start | number | 否 | 表示期望写入文件的位置,单位为字节。可选,默认文件起始位置。 | 6343| mode | number | 否 | 创建文件可写流的[选项](#openmode),必须指定如下选项中的一个,默认只写方式创建:<br/>- OpenMode.READ_ONLY(0o0):只读。<br/>- OpenMode.WRITE_ONLY(0o1):只写。<br/>- OpenMode.READ_WRITE(0o2):读写。<br/>给定如下功能选项,以按位或的方式追加,默认不给定任何额外选项:<br/>- OpenMode.CREATE(0o100):若文件不存在,则创建文件。<br/>- OpenMode.TRUNC(0o1000):如果文件存在且文件具有写权限,则将其长度裁剪为零。<br/>- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到文件末尾。<br/>- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。<br/>- OpenMode.DIR(0o200000):如果path不指向目录,则出错。不允许附加写权限。<br/>- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。<br/>- OpenMode.SYNC(0o4010000):以同步IO的方式打开文件。 | 6344