diff --git a/zh-cn/application-dev/file-management/app-file-access.md b/zh-cn/application-dev/file-management/app-file-access.md index 026b546ebc4aa5fc7ee93283e57c7c6e3bd6d33b..eb20d29a1b50fb634970f1cdf044e5f41077ab13 100644 --- a/zh-cn/application-dev/file-management/app-file-access.md +++ b/zh-cn/application-dev/file-management/app-file-access.md @@ -60,7 +60,13 @@ function createFile() { console.info("The length of str is: " + writeLen); // 从文件读取一段内容 let arrayBuffer = new ArrayBuffer(1024); - let readLen = fs.readSync(file.fd, arrayBuffer, { offset: 0 }); + class Option { + public offset: number = 0; + public length: number; + } + let option = new Option(); + option.length = arrayBuffer.byteLength; + let readLen = fs.readSync(file.fd, arrayBuffer, option); let buf = buffer.from(arrayBuffer, 0, readLen); console.info("the content of file: " + buf.toString()); // 关闭文件 @@ -89,11 +95,18 @@ function readWriteFile() { let bufSize = 4096; let readSize = 0; let buf = new ArrayBuffer(bufSize); - let readLen = fs.readSync(srcFile.fd, buf, { offset: readSize }); + class Option { + public offset: number = 0; + public length: number = bufSize; + } + let option = new Option(); + option.offset = readSize; + let readLen = fs.readSync(srcFile.fd, buf, option); while (readLen > 0) { readSize += readLen; fs.writeSync(destFile.fd, buf); - readLen = fs.readSync(srcFile.fd, buf, { offset: readSize }); + option.offset = readSize; + readLen = fs.readSync(srcFile.fd, buf, option); } // 关闭文件 fs.closeSync(srcFile); @@ -118,7 +131,7 @@ import common from '@ohos.app.ability.common'; let context = getContext(this) as common.UIAbilityContext; let filesDir = context.filesDir; -async readWriteFileWithStream() { +async function readWriteFileWithStream() { // 打开文件流 let inputStream = fs.createStreamSync(filesDir + '/test.txt', 'r+'); let outputStream = fs.createStreamSync(filesDir + '/destFile.txt', "w+"); @@ -126,11 +139,18 @@ async readWriteFileWithStream() { let bufSize = 4096; let readSize = 0; let buf = new ArrayBuffer(bufSize); - let readLen = await inputStream.read(buf, { offset: readSize }); + class Option { + public offset: number = 0; + public length: number = bufSize; + } + let option = new Option(); + option.offset = readSize; + let readLen = await inputStream.read(buf, option); readSize += readLen; while (readLen > 0) { await outputStream.write(buf); - readLen = await inputStream.read(buf, { offset: readSize }); + option.offset = readSize; + readLen = await inputStream.read(buf, option); readSize += readLen; } // 关闭文件流 @@ -157,17 +177,17 @@ let filesDir = context.filesDir; // 查看文件列表 function getListFile() { - let filter: Filter = { - suffix: ['.png', '.jpg', '.txt'], // 匹配文件后缀名为'.png','.jpg','.txt' - displayName: ['test%'], // 匹配文件全名以'test'开头 - fileSizeOver: 0, // 匹配文件大小大于等于0 - lastModifiedAfter: new Date(0).getTime(), // 匹配文件最近修改时间在1970年1月1日之后 + class ListFileOption { + public recursion: boolean = false; + public listNum: number = 0; + public filter: Filter } - let files = fs.listFileSync(filesDir, { - recursion: false, - listNum: 0, - filter: filter - }); + let option = new ListFileOption(); + option.filter.suffix = ['.png', '.jpg', '.txt']; // 匹配文件后缀名为'.png','.jpg','.txt' + option.filter.displayName = ['test%']; // 匹配文件全名以'test'开头 + option.filter.fileSizeOver = 0; // 匹配文件全名以'test'开头 + option.filter.lastModifiedAfter = new Date(0).getTime(); // 匹配文件最近修改时间在1970年1月1日之后 + let files = fs.listFileSync(filesDir, option); for (let i = 0; i < files.length; i++) { console.info(`The name of file: ${files[i]}`); } diff --git a/zh-cn/application-dev/file-management/app-file-backup.md b/zh-cn/application-dev/file-management/app-file-backup.md index 84b77faec5625e0259e83772423cb45b31319cbd..52c7c570e55ea141a5a37c56def28a920c10c708 100644 --- a/zh-cn/application-dev/file-management/app-file-backup.md +++ b/zh-cn/application-dev/file-management/app-file-backup.md @@ -107,7 +107,7 @@ // 创建SessionBackup类的实例用于备份数据 let g_session: backup.SessionBackup; function createSessionBackup() { - let sessionBackup = new backup.SessionBackup({ + let generalCallbacks: backup.GeneralCallbacks = { onFileReady: (err: BusinessError, file: backup.File) => { if (err) { console.info('onFileReady err: ' + JSON.stringify(err)); @@ -148,7 +148,8 @@ onBackupServiceDied: () => { console.info('onBackupServiceDied'); }, - }); + } + let sessionBackup = new backup.SessionBackup(generalCallbacks); return sessionBackup; } @@ -181,13 +182,14 @@ // 创建SessionRestore类的实例用于恢复数据 let g_session: backup.SessionRestore; async function publishFile(file: backup.File) { - await g_session.publishFile({ + let fileMeta: backup.FileMeta = { bundleName: file.bundleName, uri: file.uri - }); + } + await g_session.publishFile(fileMeta); } function createSessionRestore() { - let sessionRestore = new backup.SessionRestore({ + let generalCallbacks: backup.GeneralCallbacks = { onFileReady: (err: BusinessError, file: backup.File) => { if (err) { console.info('onFileReady err: ' + JSON.stringify(err)); @@ -224,7 +226,8 @@ onBackupServiceDied: () => { console.info('service died'); } - }); + } + let sessionRestore = new backup.SessionRestore(generalCallbacks); return sessionRestore; } @@ -240,14 +243,13 @@ console.info('appendBundles success'); // 添加需要恢复的应用成功后,请根据需要恢复的应用名称,调用getFileHandle接口获取待恢复应用数文件的文件句柄 // 应用待恢复数据文件数请依据实际备份文件个数为准,此处仅为请求示例 - await g_session.getFileHandle({ + let handle: backup.FileMeta = { bundleName: restoreApps[0], uri: "manage.json" - }); - await g_session.getFileHandle({ - bundleName: restoreApps[0], - uri: "1.tar" - }); + } + await g_session.getFileHandle(handle); + handle.uri = "1.tar"; + await g_session.getFileHandle(handle); console.info('getFileHandle success'); } ``` @@ -274,13 +276,14 @@ // 创建SessionRestore类的实例用于恢复数据 let g_session: backup.SessionRestore; async function publishFile(file: backup.File) { - await g_session.publishFile({ + let fileMeta: backup.FileMeta = { bundleName: file.bundleName, uri: file.uri - }); + } + await g_session.publishFile(fileMeta); } function createSessionRestore() { - let sessionRestore = new backup.SessionRestore({ + let generalCallbacks: backup.GeneralCallbacks = { onFileReady: (err: BusinessError, file: backup.File) => { if (err) { console.info('onFileReady err: ' + JSON.stringify(err)); @@ -322,7 +325,8 @@ onBackupServiceDied: () => { console.info('service died'); } - }); + } + let sessionRestore = new backup.SessionRestore(generalCallbacks); return sessionRestore; } @@ -342,19 +346,15 @@ console.info('appendBundles success'); // 开发者需要请求安装应用的文件句柄 - await g_session.getFileHandle({ + let handle: backup.FileMeta = { bundleName: restoreApps[0], uri: "/data/storage/el2/restore/bundle.hap" - }); - - await g_session.getFileHandle({ - bundleName: restoreApps[0], - uri: "manage.json" - }); - await g_session.getFileHandle({ - bundleName: restoreApps[0], - uri: "1.tar" - }); + } + await g_session.getFileHandle(handle); + handle.uri = "manage.json"; + await g_session.getFileHandle(handle); + handle.uri = "1.tar"; + await g_session.getFileHandle(handle); console.info('getFileHandle success'); } ``` diff --git a/zh-cn/application-dev/file-management/dev-user-file-manager.md b/zh-cn/application-dev/file-management/dev-user-file-manager.md index 0e6bea629835e3d9531663297e57250b2d0c27ce..800cadd042f8ab9fed9d4614d19fef9bf737cf08 100644 --- a/zh-cn/application-dev/file-management/dev-user-file-manager.md +++ b/zh-cn/application-dev/file-management/dev-user-file-manager.md @@ -24,6 +24,7 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 import fileExtensionInfo from '@ohos.file.fileExtensionInfo'; import { Filter } from '@ohos.file.fs'; import common from '@ohos.app.ability.common'; + import { BusinessError } from '@ohos.base'; ``` 其中fileAccess提供了文件基础操作的API,fileExtensionInfo提供了应用开发的关键结构体。 @@ -35,7 +36,7 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 ```ts // 获取应用上下文 - let context = getContext(this) as common.UIAbilityContext; + let context = getContext(this) as common.UIAbilityContext; // 创建连接系统内所有文件管理服务端的helper对象 let fileAccessHelperAllServer: fileAccess.FileAccessHelper; @@ -45,13 +46,14 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 if (!fileAccessHelperAllServer) { console.error("createFileAccessHelper interface returns an undefined object"); } - } catch (error) { + } catch (err) { + let error: BusinessError = err as BusinessError; console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message); } } + let rootInfos: Array = []; async function getRoots() { let rootIterator: fileAccess.RootIterator; - let rootInfos: fileAccess.RootInfo[] = []; let isDone: boolean = false; try { rootIterator = await fileAccessHelperAllServer.getRoots(); @@ -81,7 +83,7 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 ```ts // 从根目录开始 let rootInfo = rootInfos[0]; - let fileInfos: fileAccess.FileInfo[] = []; + let fileInfos: Array = []; let isDone: boolean = false; let filter: Filter = {suffix : [".txt", ".jpg", ".xlsx"]}; // 设定过滤条件 try { @@ -89,7 +91,6 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 // let fileIterator = rootInfo.scanFile(filter); // 过滤设备rootinfos[0]满足指定条件的文件信息,返回迭代对象 if (!fileIterator) { console.error("listFile interface returns an undefined object"); - return; } while (!isDone) { let result = fileIterator.next(); @@ -105,21 +106,20 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 // 从指定的目录开始 let fileInfoDir = fileInfos[0]; // fileInfoDir 表示某个目录信息 - let subFileInfos: fileAccess.FileInfo[] = []; - let isDone: boolean = false; - let filter: Filter = {suffix : [".txt", ".jpg", ".xlsx"]}; // 设定过滤条件 + let subFileInfos: Array = []; + let isDone02: boolean = false; + let filter02: Filter = {suffix : [".txt", ".jpg", ".xlsx"]}; // 设定过滤条件 try { let fileIterator = fileInfoDir.listFile(); // 遍历特定的目录fileinfo,返回迭代器对象 - // let fileIterator = rootInfo.scanFile(filter); // 过滤特定的目录fileinfo,返回迭代器对象 + // let fileIterator = rootInfo.scanFile(filter02); // 过滤特定的目录fileinfo,返回迭代器对象 if (!fileIterator) { console.error("listFile interface returns an undefined object"); - return; } - while (!isDone) { + while (!isDone02) { let result = fileIterator.next(); console.info("next result = " + JSON.stringify(result)); - isDone = result.done; - if (!isDone) + isDone02 = result.done; + if (!isDone02) subFileInfos.push(result.value); } } catch (err) { @@ -136,19 +136,20 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 // 创建文件 // 示例代码sourceUri是Download目录的fileinfo中的URI // 开发者应根据自己实际获取fileinfo的URI进行开发 - let sourceUri: string = "file://docs/storage/Users/currentUser/Download"; - let displayName: string = "file1"; - let fileUri: string; - try { - // fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取 - fileUri = await fileAccessHelper.createFile(sourceUri, displayName); - if (!fileUri) { - console.error("createFile return undefined object"); - return; - } - console.info("createFile sucess, fileUri: " + JSON.stringify(fileUri)); - } catch (err) { - let error: BusinessError = err as BusinessError; - console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message); - }; + async function creatFile() { + let sourceUri: string = "file://docs/storage/Users/currentUser/Download"; + let displayName: string = "file1"; + let fileUri: string; + try { + // fileAccessHelperAllServer 参考 fileAccess.createFileAccessHelper 示例代码获取 + fileUri = await fileAccessHelperAllServer.createFile(sourceUri, displayName); + if (!fileUri) { + console.error("createFile return undefined object"); + } + console.info("createFile sucess, fileUri: " + JSON.stringify(fileUri)); + } catch (err) { + let error: BusinessError = err as BusinessError; + console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message); + }; + } ``` diff --git a/zh-cn/application-dev/file-management/file-access-across-devices.md b/zh-cn/application-dev/file-management/file-access-across-devices.md index a2e003d977bc815847c39edeb757a221b193a849..6f9bae3fe00a220c2203344b653afcec52916a4b 100644 --- a/zh-cn/application-dev/file-management/file-access-across-devices.md +++ b/zh-cn/application-dev/file-management/file-access-across-devices.md @@ -15,6 +15,7 @@ ```ts import fs from '@ohos.file.fs'; import common from '@ohos.app.ability.common'; + import { BusinessError } from '@ohos.base'; let context = getContext(this) as common.UIAbilityContext; // 获取设备A的UIAbilityContext信息 let pathDir: string = context.distributedFilesDir; @@ -41,6 +42,7 @@ import fs from '@ohos.file.fs'; import common from '@ohos.app.ability.common'; import buffer from '@ohos.buffer'; + import { BusinessError } from '@ohos.base'; let context = getContext(this) as common.UIAbilityContext; // 获取设备B的UIAbilityContext信息 let pathDir: string = context.distributedFilesDir; @@ -53,9 +55,13 @@ // 定义接收读取数据的缓存 let arrayBuffer = new ArrayBuffer(4096); // 读取文件的内容,返回值是读取到的字节个数 - let num = fs.readSync(file.fd, arrayBuffer, { - offset: 0 - }); + class Option { + public offset: number = 0; + public length: number; + } + let option = new Option(); + option.length = arrayBuffer.byteLength; + let num = fs.readSync(file.fd, arrayBuffer, option); // 打印读取到的文件数据 let buf = buffer.from(arrayBuffer, 0, num); console.info('read result: ' + buf.toString()); diff --git a/zh-cn/application-dev/file-management/manage-external-storage.md b/zh-cn/application-dev/file-management/manage-external-storage.md index e71888cf9aeaeee7f19f9d272e4448c14ea0ad5d..b63caa523270713b33bbe0831da5863d0a4a86a3 100644 --- a/zh-cn/application-dev/file-management/manage-external-storage.md +++ b/zh-cn/application-dev/file-management/manage-external-storage.md @@ -57,16 +57,19 @@ import volumeManager from '@ohos.file.volumeManager'; import { BusinessError } from '@ohos.base'; - const subscribeInfo: CommonEvent.CommonEventSubscribeInfo = { + let subscriber: CommonEvent.CommonEventSubscriber; + async function example() { + const subscribeInfo: CommonEvent.CommonEventSubscribeInfo = { events: [ - "usual.event.data.VOLUME_REMOVED", - "usual.event.data.VOLUME_UNMOUNTED", - "usual.event.data.VOLUME_MOUNTED", - "usual.event.data.VOLUME_BAD_REMOVAL", - "usual.event.data.VOLUME_EJECT" - ] - }; - let subscriber = await CommonEvent.createSubscriber(subscribeInfo); + "usual.event.data.VOLUME_REMOVED", + "usual.event.data.VOLUME_UNMOUNTED", + "usual.event.data.VOLUME_MOUNTED", + "usual.event.data.VOLUME_BAD_REMOVAL", + "usual.event.data.VOLUME_EJECT" + ] + }; + subscriber = await CommonEvent.createSubscriber(subscribeInfo); + } ``` 3. 收到广播通知后获取卷设备信息。 diff --git a/zh-cn/application-dev/file-management/save-user-file.md b/zh-cn/application-dev/file-management/save-user-file.md index da1d42019d301c462469ee4f302841dcb4fc7c7a..1de9e27fb1350e0739a88b66c478439a22c3a032 100644 --- a/zh-cn/application-dev/file-management/save-user-file.md +++ b/zh-cn/application-dev/file-management/save-user-file.md @@ -62,8 +62,8 @@ save接口会将文件保存在文件管理器,而不是图库。 save返回的uri权限是读写权限,可以根据结果集里面的uri进行文件读写等操作。注意不能在picker的回调里直接使用此uri进行打开文件操作,需要定义一个全局变量保存uri,使用类似一个按钮去触发打开文件。 ```ts - let uris: string; - async photoViewPickerSave() { + let uris: Array; + async function photoViewPickerSave() { try { const photoSaveOptions = new picker.PhotoSaveOptions(); // 创建文件管理器保存选项实例 photoSaveOptions.newFileNames = ["PhotoViewPicker01.png"]; // 保存文件名(可选),方括号里的文件名自定义,每次不能重复,设备里已有这个文件的话,名字就需要改个不一样的,不然接口会报错 diff --git a/zh-cn/application-dev/file-management/select-user-file.md b/zh-cn/application-dev/file-management/select-user-file.md index 40ab0a19a3b519cda20da841b4c0a733a34aeccf..86ba06e451e479e30947dcf5a89c946c4a809690 100644 --- a/zh-cn/application-dev/file-management/select-user-file.md +++ b/zh-cn/application-dev/file-management/select-user-file.md @@ -107,25 +107,27 @@ > 目前DocumentSelectOptions功能不完整, 如需获取文件名称,请使用startAbilityForResult接口。 ```ts - let config: Want = { - action: 'ohos.want.action.OPEN_FILE', - parameters: { - startMode: 'choose', + async function example() { + let config: Want = { + action: 'ohos.want.action.OPEN_FILE', + parameters: { + startMode: 'choose', + } } - } - try { - let result = await context.startAbilityForResult(config, {windowMode: 1}); - if (result.resultCode !== 0) { - console.error(`documentViewPicker.select failed, code is ${result.resultCode}, message is ${result.want.parameters.message}`); - return; + try { + let result = await context.startAbilityForResult(config, {windowMode: 1}); + if (result.resultCode !== 0) { + console.error(`documentViewPicker.select failed, code is ${result.resultCode}, message is ${result.want.parameters.message}`); + return; + } + // 获取到文档文件的uri + let select_item_list = result.want.parameters.select_item_list; + // 获取到文档文件的文件名称 + let file_name_list = result.want.parameters.file_name_list; + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`); } - // 获取到文档文件的uri - let select_item_list = result.want.parameters.select_item_list; - // 获取到文档文件的文件名称 - let file_name_list = result.want.parameters.file_name_list; - } catch (err) { - let err: BusinessError = error as BusinessError; - console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`); } ``` diff --git a/zh-cn/application-dev/file-management/share-app-file.md b/zh-cn/application-dev/file-management/share-app-file.md index bdcf245eaab81ba18890d8246b419c65dc005d41..3ac269f397c9a7fcedb82b5a292765f96b5c41fa 100644 --- a/zh-cn/application-dev/file-management/share-app-file.md +++ b/zh-cn/application-dev/file-management/share-app-file.md @@ -79,8 +79,7 @@ console.error(`Invoke startAbility failed, code is ${err.code}, message is ${err.message}`); }); } - - ... + // ... } ``` @@ -123,6 +122,7 @@ // xxx.ets import fs from '@ohos.file.fs'; import Want from '@ohos.app.ability.Want'; +import { BusinessError } from '@ohos.base'; function getShareFile() { try { diff --git a/zh-cn/application-dev/reference/apis/js-apis-file-picker.md b/zh-cn/application-dev/reference/apis/js-apis-file-picker.md index fcb1600558297074bc27f5665ed0fcf2531417b4..f20607c4bd9753be53a7e1c3e1751aee18d63245 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-file-picker.md +++ b/zh-cn/application-dev/reference/apis/js-apis-file-picker.md @@ -65,7 +65,7 @@ async function example01() { }); } catch (error) { let err: BusinessError = error as BusinessError; - console.error('PhotoViewPicker failed with err: ' + + JSON.stringify(err)); + console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -207,7 +207,7 @@ async function example05() { let photoPicker = new picker.PhotoViewPicker(); photoPicker.save(PhotoSaveOptions, (err: BusinessError, PhotoSaveResult: Array) => { if (err) { - console.error('PhotoViewPicker.save failed with err: ' JSON.stringify(err)); + console.error('PhotoViewPicker.save failed with err: ' + JSON.stringify(err)); return; } console.info('PhotoViewPicker.save successfully, PhotoSaveResult uri: ' + JSON.stringify(PhotoSaveResult));