From b59339f3385a3422eed0576aa78e9f600c7e29a1 Mon Sep 17 00:00:00 2001 From: wangweiyuan2 Date: Fri, 9 May 2025 20:13:02 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wangweiyuan2 --- .../AppFileBackup/build-profile.json5 | 2 +- .../main/ets/backuprestore/BackupRestore.ets | 11 ++- .../AppFileBackup/entry/src/main/module.json5 | 2 + .../src/ohosTest/ets/test/FileBackup.test.ets | 2 +- .../DistributedFileSample/build-profile.json5 | 2 +- .../entry/src/main/ets/pages/Index.ets | 43 +++++++-- .../FileBackupExtension/build-profile.json5 | 2 +- .../src/main/ets/common/BackupExtension.ets | 4 +- .../entry/src/main/module.json5 | 2 + .../CoreFile/FileSample/build-profile.json5 | 2 +- .../entry/src/main/ets/fileFs/FileFs.ets | 94 +++++++++++-------- .../entry/src/main/ets/pages/Index.ets | 24 ++++- .../FileSample/entry/src/main/module.json5 | 3 +- .../NDKAppFileSample/build-profile.json5 | 2 +- .../entry/src/main/cpp/napi_init.cpp | 14 ++- .../CoreFile/SandBoxShare/build-profile.json5 | 2 +- .../entry/src/main/ets/fileFs/FileFs.ets | 53 ++++++----- .../build-profile.json5 | 2 - .../pages/FileManagerApplication.ets | 12 ++- .../pages/ListeningForDeviceOnline.ets | 25 +++-- .../entry/src/main/module.json5 | 18 ++-- .../FileUriDevelopment_C/build-profile.json5 | 2 - .../entry/src/main/cpp/napi_init.cpp | 43 ++++++++- .../build-profile.json5 | 2 - .../entry/src/main/ets/pages/Index.ets | 13 ++- .../SavingUserFiles/build-profile.json5 | 2 - .../entry/src/main/ets/pages/Index.ets | 23 +++++ .../SelectingUserFiles/build-profile.json5 | 2 - .../entry/src/main/ets/pages/Index.ets | 27 ++++++ .../UserFile/UserFileURI/build-profile.json5 | 2 - .../entry/src/main/ets/pages/Index.ets | 16 +++- 31 files changed, 329 insertions(+), 124 deletions(-) diff --git a/code/DocsSample/CoreFile/AppFileBackup/build-profile.json5 b/code/DocsSample/CoreFile/AppFileBackup/build-profile.json5 index f07cd5aa4c..ed6ac10fe4 100644 --- a/code/DocsSample/CoreFile/AppFileBackup/build-profile.json5 +++ b/code/DocsSample/CoreFile/AppFileBackup/build-profile.json5 @@ -38,7 +38,7 @@ { "name": "release" } - ] + ], }, "modules": [ { diff --git a/code/DocsSample/CoreFile/AppFileBackup/entry/src/main/ets/backuprestore/BackupRestore.ets b/code/DocsSample/CoreFile/AppFileBackup/entry/src/main/ets/backuprestore/BackupRestore.ets index 260cdbeade..5226e9e780 100644 --- a/code/DocsSample/CoreFile/AppFileBackup/entry/src/main/ets/backuprestore/BackupRestore.ets +++ b/code/DocsSample/CoreFile/AppFileBackup/entry/src/main/ets/backuprestore/BackupRestore.ets @@ -13,6 +13,9 @@ * limitations under the License. */ +// [Start get_local_cap_ability] +// [Start session_backup] +// [Start session_restore] import { fileIo as fs, ReadOptions } from '@kit.CoreFileKit'; import backup from '@ohos.file.backup'; import { common } from '@kit.AbilityKit'; @@ -20,7 +23,9 @@ import { BusinessError } from '@ohos.base'; import buffer from '@ohos.buffer'; import Logger from '../common/Logger'; +// [StartExclude get_local_cap_ability] const BUFFER: number = 1024; // 读写文件的缓冲区 +// [EndExclude get_local_cap_ability] // 获取应用文件沙箱路径 let context = getContext(this) as common.UIAbilityContext; @@ -37,6 +42,7 @@ export async function getLocalCapabilities(): Promise { Logger.info('getLocalCapabilities success'); let fpath = filesDir + '/localCapabilities.json'; fs.copyFileSync(fileData.fd, fpath); + // [StartExclude get_local_cap_ability] let file = fs.openSync(fpath, fs.OpenMode.READ_WRITE); // 从文件中读取一段内容 let arrayBuffer = new ArrayBuffer(BUFFER); @@ -48,11 +54,13 @@ export async function getLocalCapabilities(): Promise { // 这个 buf 对象是 arrayBuffer 中从位置 0 开始的前 readLen 字节 let buf = buffer.from(arrayBuffer, 0, readLen); Logger.info('the content of file: ' + buf.toString()); + // [EndExclude get_local_cap_ability] fs.closeSync(fileData.fd); } catch (error) { Logger.error('getLocalCapabilities failed with err: ' + JSON.stringify(error)); } } +// [End get_local_cap_ability] // 应用备份数据 function createSessionBackup(): backup.SessionBackup { @@ -121,6 +129,7 @@ export async function release() { console.error('release failed with err: ' + JSON.stringify(err)); } } +// [End session_backup] export async function sessionBackup(): Promise { gSession = createSessionBackup(); @@ -228,4 +237,4 @@ export async function sessionRestore(): Promise { await gSessionRestore.getFileHandle(handle); Logger.info('getFileHandle success'); } - +// [End session_restore] diff --git a/code/DocsSample/CoreFile/AppFileBackup/entry/src/main/module.json5 b/code/DocsSample/CoreFile/AppFileBackup/entry/src/main/module.json5 index 37d81ace51..3e0bb8ef38 100644 --- a/code/DocsSample/CoreFile/AppFileBackup/entry/src/main/module.json5 +++ b/code/DocsSample/CoreFile/AppFileBackup/entry/src/main/module.json5 @@ -62,6 +62,7 @@ ] } ], + // [Start request_permission_backup] "requestPermissions": [ { "name": "ohos.permission.BACKUP", @@ -73,5 +74,6 @@ } } ] + // [End request_permission_backup] } } \ No newline at end of file diff --git a/code/DocsSample/CoreFile/AppFileBackup/entry/src/ohosTest/ets/test/FileBackup.test.ets b/code/DocsSample/CoreFile/AppFileBackup/entry/src/ohosTest/ets/test/FileBackup.test.ets index 91fc8ab148..65ef84741d 100644 --- a/code/DocsSample/CoreFile/AppFileBackup/entry/src/ohosTest/ets/test/FileBackup.test.ets +++ b/code/DocsSample/CoreFile/AppFileBackup/entry/src/ohosTest/ets/test/FileBackup.test.ets @@ -172,9 +172,9 @@ export default function FileBackupRestoreTest() { bundleName: 'com.samples.filebackupextension', abilityName: 'EntryAbility' }; - await DELEGATOR.startAbility(want); let driver: Driver = Driver.create(); await driver.delayMs(DELAY_TIME); + await DELEGATOR.startAbility(want); hilog.info(DOMAIN, TAG, BUNDLE + 'get top ability'); done(); hilog.info(DOMAIN, TAG, BUNDLE + 'StartAbility_003 end'); diff --git a/code/DocsSample/CoreFile/DistributedFileSample/build-profile.json5 b/code/DocsSample/CoreFile/DistributedFileSample/build-profile.json5 index f07cd5aa4c..ed6ac10fe4 100644 --- a/code/DocsSample/CoreFile/DistributedFileSample/build-profile.json5 +++ b/code/DocsSample/CoreFile/DistributedFileSample/build-profile.json5 @@ -38,7 +38,7 @@ { "name": "release" } - ] + ], }, "modules": [ { diff --git a/code/DocsSample/CoreFile/DistributedFileSample/entry/src/main/ets/pages/Index.ets b/code/DocsSample/CoreFile/DistributedFileSample/entry/src/main/ets/pages/Index.ets index 9baa625e33..8537950fd3 100644 --- a/code/DocsSample/CoreFile/DistributedFileSample/entry/src/main/ets/pages/Index.ets +++ b/code/DocsSample/CoreFile/DistributedFileSample/entry/src/main/ets/pages/Index.ets @@ -13,6 +13,9 @@ * limitations under the License. */ +// [Start cross_device_file_access_B] +// [Start import_interface_distributed] +// [Start dis_mount_public_dir] import { BusinessError } from '@kit.BasicServicesKit'; import { common, abilityAccessCtrl } from '@kit.AbilityKit'; import { distributedDeviceManager } from '@kit.DistributedServiceKit'; @@ -21,22 +24,17 @@ import { buffer } from '@kit.ArkTS'; import Logger from '../common/Logger'; import { showToast } from '../common/ShowToast'; +// [Start import_interface_distributed] const BUFFER: number = 4096; // 读写文件的缓冲区 const DELAY: number = 1000; // 延时1秒 const MARGIN: number = 5; // 组件的间隔 +// [Start cross_device_file_access_A] let context = getContext(this) as common.UIAbilityContext; // 获取UIAbilityContext信息 let pathDir: string = context.filesDir; // 应用沙箱路径 let distributedPathDir: string = context.distributedFilesDir; // 应用分布式路径 let atManager = abilityAccessCtrl.createAtManager(); -// 定义访问公共文件目录的回调 -let listeners: fs.DfsListeners = { - onStatus: (networkId: string, status: number): void => { - Logger.info('Failed to access public directory'); - } -} - // 设备A上在分布式路径下创建测试文件,并写入内容 function createFile(path: string, fileName: string): void { let filePath = path + '/' + fileName + '.txt'; @@ -48,6 +46,9 @@ function createFile(path: string, fileName: string): void { fs.closeSync(file.fd); } +// [End cross_device_file_access_A] + +// [Start set_security_label] // 打开文件并设置文件数据等级为‘s0’ function setFileLv(path: string): void { let file = fs.openSync(path, fs.OpenMode.READ_ONLY); @@ -60,6 +61,16 @@ function setFileLv(path: string): void { }); } +// [End set_security_label] + +// 定义访问公共文件目录的回调 +let listeners: fs.DfsListeners = { + onStatus: (networkId: string, status: number): void => { + Logger.info('Failed to access public directory'); + } +} + +// [StartExclude cross_device_file_access_B] // 申请多设备协同权限 async function applyPermission() { try { @@ -73,12 +84,17 @@ async function applyPermission() { } } +// [EndExclude cross_device_file_access_B] + // 设备B主动向设备A发起建链,建链成功后设备B可在分布式路径下读取测试文件 async function mountPublicDir() { + // [StartExclude cross_device_file_access_B] // 通过分布式设备管理的接口获取设备A的networkId信息 let dmInstance = distributedDeviceManager.createDeviceManager('ohos.samples.distributedmusicplayer'); let deviceInfoList: distributedDeviceManager.DeviceBasicInfo[] = dmInstance.getAvailableDeviceListSync(); let networkId = deviceInfoList[0].networkId; // 0表示可信设备列表中第一台设备 + // [EndExclude cross_device_file_access_B] + // 访问并挂载公共文件目录 fs.connectDfs(networkId, listeners).then(() => { Logger.info('Success to connectDfs'); @@ -115,6 +131,8 @@ async function mountPublicDir() { }); } +// [Start cross_device_file_access_B] + // 取消公共文件目录挂载,断开链路。 function disMountPublicDir(): void { // 通过分布式设备管理的接口获取设备A的networkId信息 @@ -130,6 +148,9 @@ function disMountPublicDir(): void { }) } +// [End dis_mount_public_dir] + +// [Start copy_sand_to_distributed] // 将A设备的待拷贝沙箱文件,拷贝到A设备的分布式路径下。 function copySandFile(): void { // 待拷贝文件沙箱路径 @@ -152,8 +173,10 @@ function copySandFile(): void { fs.copy(srcUri, destUri).then(() => { Logger.info('Succeeded in copying---. '); Logger.info('src: ' + srcUri + 'dest: ' + destUri); + // [StartExclude copy_sand_to_distributed] setFileLv(distributedPathDir + '/src.txt'); showToast('Succeed copy from sandDir to distributedDir', DELAY); + // [EndExclude copy_sand_to_distributed] }).catch((error: BusinessError) => { let err: BusinessError = error as BusinessError; Logger.error(`Failed to copy. Code: ${err.code}, message: ${err.message}`); @@ -164,6 +187,9 @@ function copySandFile(): void { } } +// [End copy_sand_to_distributed] + +// [End copy_distributed_to_sand] // B设备在获取A端沙箱文件时,从B设备的分布式路径下将对应的文件拷贝走,以此完成跨设备拷贝。 function copyDistributedFile(): void { // 待拷贝文件的目标沙箱路径 @@ -195,6 +221,8 @@ function copyDistributedFile(): void { } } +// [End copy_distributed_to_sand] + // 查看文件列表 function getListFile(pathDir: string): void { let listFileOption: ListFileOptions = { @@ -217,7 +245,6 @@ function getListFile(pathDir: string): void { @Entry @Component struct Distributed { - build() { Column() { Row() { diff --git a/code/DocsSample/CoreFile/FileBackupExtension/build-profile.json5 b/code/DocsSample/CoreFile/FileBackupExtension/build-profile.json5 index f07cd5aa4c..ed6ac10fe4 100644 --- a/code/DocsSample/CoreFile/FileBackupExtension/build-profile.json5 +++ b/code/DocsSample/CoreFile/FileBackupExtension/build-profile.json5 @@ -38,7 +38,7 @@ { "name": "release" } - ] + ], }, "modules": [ { diff --git a/code/DocsSample/CoreFile/FileBackupExtension/entry/src/main/ets/common/BackupExtension.ets b/code/DocsSample/CoreFile/FileBackupExtension/entry/src/main/ets/common/BackupExtension.ets index 358422071c..27a9165930 100644 --- a/code/DocsSample/CoreFile/FileBackupExtension/entry/src/main/ets/common/BackupExtension.ets +++ b/code/DocsSample/CoreFile/FileBackupExtension/entry/src/main/ets/common/BackupExtension.ets @@ -13,9 +13,11 @@ * limitations under the License. */ +// [Start on_backup_restore] import BackupExtensionAbility, { BundleVersion } from '@ohos.application.BackupExtensionAbility'; import Logger from '../common/Logger'; + interface ErrorInfo { type: string, errorCode: number, @@ -56,4 +58,4 @@ class BackupExt extends BackupExtensionAbility { return JSON.stringify(errorInfo); } } - +// [End on_backup_restore] diff --git a/code/DocsSample/CoreFile/FileBackupExtension/entry/src/main/module.json5 b/code/DocsSample/CoreFile/FileBackupExtension/entry/src/main/module.json5 index e6a87f1283..f683de16b7 100644 --- a/code/DocsSample/CoreFile/FileBackupExtension/entry/src/main/module.json5 +++ b/code/DocsSample/CoreFile/FileBackupExtension/entry/src/main/module.json5 @@ -50,6 +50,7 @@ ] } ], + // [Start extension_abilities] "extensionAbilities": [ { "name": "BackupExtension", @@ -64,5 +65,6 @@ ] } ] + // [End extension_abilities] } } \ No newline at end of file diff --git a/code/DocsSample/CoreFile/FileSample/build-profile.json5 b/code/DocsSample/CoreFile/FileSample/build-profile.json5 index 5dea84a998..6eb23a9a54 100644 --- a/code/DocsSample/CoreFile/FileSample/build-profile.json5 +++ b/code/DocsSample/CoreFile/FileSample/build-profile.json5 @@ -32,7 +32,7 @@ { "name": "release" } - ] + ], }, "modules": [ { diff --git a/code/DocsSample/CoreFile/FileSample/entry/src/main/ets/fileFs/FileFs.ets b/code/DocsSample/CoreFile/FileSample/entry/src/main/ets/fileFs/FileFs.ets index 1206bd1564..291a8eda75 100644 --- a/code/DocsSample/CoreFile/FileSample/entry/src/main/ets/fileFs/FileFs.ets +++ b/code/DocsSample/CoreFile/FileSample/entry/src/main/ets/fileFs/FileFs.ets @@ -13,6 +13,12 @@ * limitations under the License. */ +// [Start create_Write_File] +// [Start read_Write_File] +// [Start streams_Read_Write_File] +// [Start view_File_List] +// [Start streams_file] +// [Start hash_File_Stream] import { fileIo as fs, ReadOptions, WriteOptions, ListFileOptions } from '@kit.CoreFileKit'; import { buffer } from '@kit.ArkTS'; import { common } from '@kit.AbilityKit'; @@ -23,9 +29,12 @@ import Logger from '../common/Logger'; let context = getContext(this) as common.UIAbilityContext; let filesDir = context.filesDir; +// [StartExclude create_Write_File] const BUFFER: number = 1024; // 读取文件数据的缓冲区大小 const READSIZE: number = 0; // 初始化读取的字节数为 0 +// [EndExclude create_Write_File] + export function createFile(): string { // 新建并打开文件 let file = fs.openSync(filesDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); @@ -47,6 +56,8 @@ export function createFile(): string { return str; } +// [End create_Write_File] + // 读取文件内容并写入到另一个文件 test.txt => testFile.txt export function readWriteFile(): void { // 打开文件 @@ -76,42 +87,7 @@ export function readWriteFile(): void { fs.closeSync(destFile); } -// 根据文件名读取文件内容 -export function readFile(fileName: string): string { - let file = fs.openSync(filesDir + '/' + fileName + '.txt', fs.OpenMode.READ_ONLY); - let arrayBuffer = new ArrayBuffer(BUFFER); - let readOptions: ReadOptions = { - offset: 0, // 从文件的开头开始读取 - length: arrayBuffer.byteLength - }; - let readLen = fs.readSync(file.fd, arrayBuffer, readOptions); - // 这个 buf 对象是 arrayBuffer 中从位置 0 开始的前 readLen 字节 - let buf = buffer.from(arrayBuffer, 0, readLen); - Logger.info('the content of file: ' + buf.toString()); - let str = 'the content of file: ' + buf.toString(); - return str; -} - -// 查看文件列表 -export function getListFile(): string { - let str = ''; - let listFileOption: ListFileOptions = { - recursion: false, - listNum: 0, // 0 表示不限制文件数量 - filter: { - suffix: ['.png', '.jpg', '.txt', '.jpeg', '.json'], - displayName: ['*'], - fileSizeOver: 0, // 0 表示列出所有文件,不限制文件大小 - lastModifiedAfter: new Date(0).getTime() // 返回的时间戳是0 - } - }; - let files = fs.listFileSync(filesDir, listFileOption); - for (let i = 0; i < files.length; i++) { - Logger.info(`The name of file: ${files[i]}`); - str += files[i] + '\n'; - } - return str; -} +// [End read_Write_File] // 以流的形式读写文件test.txt => destFile.txt export async function readWriteFileWithStream(): Promise { @@ -140,6 +116,31 @@ export async function readWriteFileWithStream(): Promise { outputStream.closeSync(); } +// [End streams_Read_Write_File] + +// 查看文件列表 +export function getListFile(): string { + let str = ''; + let listFileOption: ListFileOptions = { + recursion: false, + listNum: 0, // 0 表示不限制文件数量 + filter: { + suffix: ['.png', '.jpg', '.txt', '.jpeg', '.json'], + displayName: ['*'], + fileSizeOver: 0, // 0 表示列出所有文件,不限制文件大小 + lastModifiedAfter: new Date(0).getTime() // 返回的时间戳是0 + } + }; + let files = fs.listFileSync(filesDir, listFileOption); + for (let i = 0; i < files.length; i++) { + Logger.info(`The name of file: ${files[i]}`); + str += files[i] + '\n'; + } + return str; +} + +// [End view_File_List] + // 使用文件流 export function copyFileWithReadable(): void { // 创建文件可读流 @@ -157,7 +158,6 @@ export function copyFileWithReadable(): void { } export function copyFileWithData(): void { - // 创建文件可读流 const rs = fs.createReadStream(`${filesDir}/testFile.txt`); // 创建文件可写流 @@ -172,6 +172,8 @@ export function copyFileWithData(): void { }); } +// [End streams_file] + // 使用文件哈希流 export function hashFileWithStream() { const filePath = `${filesDir}/test.txt`; @@ -189,4 +191,22 @@ export function hashFileWithStream() { const fileHash = await hash.hash(filePath, 'sha256'); Logger.info(`hashResult: ${hashResult}, fileHash: ${fileHash}`); }); +} + +// [End hash_File_Stream] + +// 根据文件名读取文件内容 +export function readFile(fileName: string): string { + let file = fs.openSync(filesDir + '/' + fileName + '.txt', fs.OpenMode.READ_ONLY); + let arrayBuffer = new ArrayBuffer(BUFFER); + let readOptions: ReadOptions = { + offset: 0, // 从文件的开头开始读取 + length: arrayBuffer.byteLength + }; + let readLen = fs.readSync(file.fd, arrayBuffer, readOptions); + // 这个 buf 对象是 arrayBuffer 中从位置 0 开始的前 readLen 字节 + let buf = buffer.from(arrayBuffer, 0, readLen); + Logger.info('the content of file: ' + buf.toString()); + let str = 'the content of file: ' + buf.toString(); + return str; } \ No newline at end of file diff --git a/code/DocsSample/CoreFile/FileSample/entry/src/main/ets/pages/Index.ets b/code/DocsSample/CoreFile/FileSample/entry/src/main/ets/pages/Index.ets index f0ce997e65..58dca08ce3 100644 --- a/code/DocsSample/CoreFile/FileSample/entry/src/main/ets/pages/Index.ets +++ b/code/DocsSample/CoreFile/FileSample/entry/src/main/ets/pages/Index.ets @@ -13,6 +13,7 @@ * limitations under the License. */ +// [Start import_starf_storageStatistics] import { common } from '@kit.AbilityKit'; import { statfs } from '@kit.CoreFileKit'; import { buffer } from '@kit.ArkTS'; @@ -31,27 +32,31 @@ import { hashFileWithStream } from '../fileFs/FileFs'; +// [StartExclude import_starf_storageStatistics] const BUFFER: number = 1024; // 读取文件缓冲区 const MARGIN = 5; // 组件间的间隔 +// [EndExclude import_starf_storageStatistics] // 获取应用文件路径 let context = getContext(this) as common.UIAbilityContext; let filesDir = context.filesDir; +// [End import_starf_storageStatistics] +// [Start get_share_file] function getShareFile(): string { let strFile = ''; try { let URI: string | undefined = AppStorage.get('URI'); - let uri = URI; - if (uri == null || uri == undefined) { + if (URI === null || URI === undefined) { Logger.info('uri is invalid'); let str = 'uri is invalid'; return str; } try { // 根据需要对被分享文件的URI进行相应操作。例如读写的方式打开URI获取file对象 - let file = fs.openSync(uri, fs.OpenMode.READ_WRITE); + let file = fs.openSync(URI, fs.OpenMode.READ_WRITE); Logger.info('open file successfully!'); + // [StartExclude get_share_file] // 1024为读取文件内容的缓冲区大小 let arrayBuffer = new ArrayBuffer(BUFFER); let readOptions: ReadOptions = { @@ -65,6 +70,7 @@ function getShareFile(): string { // 关闭文件 strFile = 'the content of file: ' + buf.toString(); fs.closeSync(file); + // [EndExclude get_share_file] } catch (err) { let error: BusinessError = err as BusinessError; Logger.info(`Invoke openSync failed, code is ${error.code}, message is ${error.message}`); @@ -76,6 +82,8 @@ function getShareFile(): string { return strFile; } +// [End get_share_file] + @Entry @Component export default struct Index { @@ -134,28 +142,36 @@ export default struct Index { .height('6%') .margin(MARGIN) .onClick(() => { + // [Start statfs_get_FreeSize] statfs.getFreeSize(filesDir, (err: BusinessError, number: number) => { if (err) { Logger.info(`Invoke getFreeSize failed, code is ${err.code}, message is ${err.message}`); } else { Logger.info(`Invoke getFreeSize succeeded, size is ${number}`); + // [StartExclude statfs_get_FreeSize] this.message += 'The size of the remaining space in the file system data: ' + number.toString() + '\n'; + // [EndExclude statfs_get_FreeSize] } }); + // [End statfs_get_FreeSize] }) Button($r('app.string.appStorageSpaceSize')) .width('80%') .height('6%') .margin(MARGIN) .onClick(() => { + // [Start storageStatistics_getCurrentBundleStats] storageStatistics.getCurrentBundleStats((err: BusinessError, bundleStats: storageStatistics.BundleStats) => { if (err) { Logger.info(`Invoke getCurrentBundleStats failed, code is ${err.code}, message is ${err.message}`); } else { Logger.info(`Invoke getCurrentBundleStats succeeded, appsize is ${bundleStats.appSize}`); + // [StartExclude storageStatistics_getCurrentBundleStats] this.message += 'The size of the storage space in the system: ' + bundleStats.appSize.toString() + '\n'; + // [EndExclude storageStatistics_getCurrentBundleStats] } }); + // [End storageStatistics_getCurrentBundleStats] }) Row() { Button($r('app.string.hash')) @@ -167,7 +183,7 @@ export default struct Index { Button($r('app.string.getShareFile')) .onClick(() => { this.message += getShareFile() + '\n'; - let str: string | undefined = AppStorage.get('content'); + let str: string | undefined = AppStorage.get('URI'); this.message += str + '\n'; }) .width('50%') diff --git a/code/DocsSample/CoreFile/FileSample/entry/src/main/module.json5 b/code/DocsSample/CoreFile/FileSample/entry/src/main/module.json5 index 19c80c4865..c69216e156 100644 --- a/code/DocsSample/CoreFile/FileSample/entry/src/main/module.json5 +++ b/code/DocsSample/CoreFile/FileSample/entry/src/main/module.json5 @@ -68,6 +68,7 @@ } ] } - ] + ], + } } \ No newline at end of file diff --git a/code/DocsSample/CoreFile/NDKAppFileSample/build-profile.json5 b/code/DocsSample/CoreFile/NDKAppFileSample/build-profile.json5 index 41b14ba995..429d666120 100644 --- a/code/DocsSample/CoreFile/NDKAppFileSample/build-profile.json5 +++ b/code/DocsSample/CoreFile/NDKAppFileSample/build-profile.json5 @@ -44,7 +44,7 @@ { "name": "release" } - ] + ], }, "modules": [ { diff --git a/code/DocsSample/CoreFile/NDKAppFileSample/entry/src/main/cpp/napi_init.cpp b/code/DocsSample/CoreFile/NDKAppFileSample/entry/src/main/cpp/napi_init.cpp index 308fd7703c..8fa5a676a9 100644 --- a/code/DocsSample/CoreFile/NDKAppFileSample/entry/src/main/cpp/napi_init.cpp +++ b/code/DocsSample/CoreFile/NDKAppFileSample/entry/src/main/cpp/napi_init.cpp @@ -21,8 +21,9 @@ #undef LOG_TAG #define LOG_TAG "Sample_NDKAppFileAccess" -static napi_value GetFileLocation(napi_env env, napi_callback_info info) -{ +// [Start get_file_location] +static napi_value GetFileLocation(napi_env env, napi_callback_info info) { + // [StartExclude get_file_location] size_t argc = 1; napi_value args[1] = {nullptr}; @@ -42,12 +43,15 @@ static napi_value GetFileLocation(napi_env env, napi_callback_info info) // 获取字符串的长度 size_t strLength = 0; napi_get_value_string_utf8(env, args[0], nullptr, 0, &strLength); + // [EndExclude get_file_location] // 为 char* uri 分配内存 char *uri = new char[strLength + 1]; // +1 for null terminator // 将 JavaScript 字符串复制到 uri + // [StartExclude get_file_location] napi_get_value_string_utf8(env, args[0], uri, strLength + 1, &strLength); // 输出 uri 字符串(用于调试) OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.WatcherType=OnTrigger: %{public}s", uri); + // [EndExclude get_file_location] FileIO_FileLocation location; FileManagement_ErrCode ret = OH_FileIO_GetFileLocation(uri, strlen(uri), &location); if (ret == 0) { @@ -61,14 +65,16 @@ static napi_value GetFileLocation(napi_env env, napi_callback_info info) } else { OH_LOG_INFO(LogType::LOG_APP, "GetFileLocation failed, error code is %{public}d", ret); } + // [StartExclude get_file_location] // 如果需要返回值,可以创建一个 JavaScript 字符串返回 napi_value result; napi_create_string_utf8(env, uri, strLength, &result); return result; + // [EndExclude get_file_location] } +// [End get_file_location] EXTERN_C_START -static napi_value Init(napi_env env, napi_value exports) -{ +static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor desc[] = { {"getFileLocation", nullptr, GetFileLocation, nullptr, nullptr, nullptr, napi_default, nullptr}}; napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); diff --git a/code/DocsSample/CoreFile/SandBoxShare/build-profile.json5 b/code/DocsSample/CoreFile/SandBoxShare/build-profile.json5 index 5dea84a998..6eb23a9a54 100644 --- a/code/DocsSample/CoreFile/SandBoxShare/build-profile.json5 +++ b/code/DocsSample/CoreFile/SandBoxShare/build-profile.json5 @@ -32,7 +32,7 @@ { "name": "release" } - ] + ], }, "modules": [ { diff --git a/code/DocsSample/CoreFile/SandBoxShare/entry/src/main/ets/fileFs/FileFs.ets b/code/DocsSample/CoreFile/SandBoxShare/entry/src/main/ets/fileFs/FileFs.ets index d2eb3f9260..7ff68ab532 100644 --- a/code/DocsSample/CoreFile/SandBoxShare/entry/src/main/ets/fileFs/FileFs.ets +++ b/code/DocsSample/CoreFile/SandBoxShare/entry/src/main/ets/fileFs/FileFs.ets @@ -13,6 +13,8 @@ * limitations under the License. */ +// [Start application_file_share] +// [Start get_uri] import { common } from '@kit.AbilityKit'; import { fileIo as fs, ReadOptions, ListFileOptions } from '@kit.CoreFileKit'; import Logger from '../common/Logger'; @@ -25,6 +27,32 @@ import { BusinessError } from '@kit.BasicServicesKit'; let context = getContext(this) as common.UIAbilityContext; let filesDir = context.filesDir; +// 分享应用文件 +export async function shareFile(fileName: string): Promise { + // 获取文件的沙箱路径 + let pathInSandbox = context.filesDir + '/' + fileName + '.txt'; + // 将沙箱路径转换为uri + let uri = fileUri.getUriFromPath(pathInSandbox); + // [End get_uri] + Logger.info('FilePath is : ' + uri); + let want: Want = { + // 配置被分享文件的读写权限,例如对被分享应用进行读写授权 + flags: wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION | wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, + // 配置分享应用的隐式拉起规则 + action: 'ohos.want.action.sendData', + uri: uri, + type: 'text/plain', + }; + await context.startAbility(want) + .then(() => { + Logger.info('Invoke getCurrentBundleStats succeeded.'); + }) + .catch((err: BusinessError) => { + Logger.error(`Invoke startAbility failed, code is ${err.code}, message is ${err.message}`); + }); +} + +// [End application_file_share] // 新建并读写一个文件test1.txt export function createFile(): number { // 新建并打开文件 @@ -75,28 +103,3 @@ export function getListFile(): string { } return str; } - -// 分享应用文件 -export async function shareFile(fileName: string): Promise { - console.info('shareFile start'); - // 获取文件的沙箱路径 - let pathInSandbox = context.filesDir + '/' + fileName + '.txt'; - // 将沙箱路径转换为uri - let uri = fileUri.getUriFromPath(pathInSandbox); - Logger.info('FilePath is : ' + uri); - let want: Want = { - // 配置被分享文件的读写权限,例如对被分享应用进行读写授权 - flags: wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION | wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, - // 配置分享应用的隐式拉起规则 - action: 'ohos.want.action.sendData', - uri: uri, - type: 'text/plain', - }; - await context.startAbility(want) - .then(() => { - Logger.info('Invoke getCurrentBundleStats succeeded.'); - }) - .catch((err: BusinessError) => { - Logger.error(`Invoke startAbility failed, code is ${err.code}, message is ${err.message}`); - }); -} \ No newline at end of file diff --git a/code/DocsSample/CoreFile/UserFile/DevelopingFileManagerApplication/build-profile.json5 b/code/DocsSample/CoreFile/UserFile/DevelopingFileManagerApplication/build-profile.json5 index 6ba10a5d9b..099dfbac6e 100644 --- a/code/DocsSample/CoreFile/UserFile/DevelopingFileManagerApplication/build-profile.json5 +++ b/code/DocsSample/CoreFile/UserFile/DevelopingFileManagerApplication/build-profile.json5 @@ -15,8 +15,6 @@ { "app": { - "signingConfigs": [ - ], "products": [ { "name": "default", diff --git a/code/DocsSample/CoreFile/UserFile/DevelopingFileManagerApplication/entry/src/main/ets/filemanager/pages/FileManagerApplication.ets b/code/DocsSample/CoreFile/UserFile/DevelopingFileManagerApplication/entry/src/main/ets/filemanager/pages/FileManagerApplication.ets index 41e8c8fde8..be9e30693c 100644 --- a/code/DocsSample/CoreFile/UserFile/DevelopingFileManagerApplication/entry/src/main/ets/filemanager/pages/FileManagerApplication.ets +++ b/code/DocsSample/CoreFile/UserFile/DevelopingFileManagerApplication/entry/src/main/ets/filemanager/pages/FileManagerApplication.ets @@ -13,10 +13,12 @@ * limitations under the License. */ +// [Start import_interface_file_manager] import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; import { Filter, fileAccess } from '@kit.CoreFileKit'; import Logger from '../../common/Logger'; +// [End import_interface_file_manager] let rootInfos: fileAccess.RootInfo[] = []; let rootInfo: fileAccess.RootInfo = rootInfos[0]; @@ -30,9 +32,10 @@ let isDone02: boolean = false; let sourceUri: string = 'file://docs/storage/Users/currentUser/Download'; let displayName: string = 'file2'; let fileUri: string = ''; + +// [Start file_access_root_info] // 获取应用上下文 let context = getContext(this) as common.UIAbilityContext; - // 创建连接系统内所有文件管理服务端的helper对象 let fileAccessHelperAllServer: fileAccess.FileAccessHelper; @@ -47,6 +50,7 @@ function createFileAccessHelper(): void { Logger.error('createFileAccessHelper failed, errCode:' + error.code + ', errMessage:' + error.message); } } +// [End file_access_root_info] @Entry @Component @@ -85,6 +89,7 @@ struct Index { .backgroundColor($r('app.color.lightGrayColor')) // 背景颜色为浅灰色 } + // [Start file_access_get_root] async getRoots(): Promise { try { rootIterator = await fileAccessHelperAllServer.getRoots(); @@ -105,7 +110,9 @@ struct Index { Logger.error('getRoots failed, errCode:' + error.code + ', errMessage:' + error.message); } } + // [End file_access_get_root] + // [Start file_info_dir] async listRootFiles(): Promise { try { let fileIterator = rootInfo.listFile(); // 遍历设备rootinfos[0]的根目录,返回迭代器对象 @@ -145,7 +152,9 @@ struct Index { Logger.error('listFile failed, errCode:' + error.code + ', errMessage:' + error.message); } } + // [End file_info_dir] + // [Start create_file_promise] async creatFile(): Promise { try { // fileAccessHelperAllServer 参考 fileAccess.createFileAccessHelper 示例代码获取 @@ -161,6 +170,7 @@ struct Index { } ; } + // [End create_file_promise] } // 在组件加载时创建文件访问助手 diff --git a/code/DocsSample/CoreFile/UserFile/DevelopingFileManagerApplication/entry/src/main/ets/filemanager/pages/ListeningForDeviceOnline.ets b/code/DocsSample/CoreFile/UserFile/DevelopingFileManagerApplication/entry/src/main/ets/filemanager/pages/ListeningForDeviceOnline.ets index 1e98768371..061fae801e 100644 --- a/code/DocsSample/CoreFile/UserFile/DevelopingFileManagerApplication/entry/src/main/ets/filemanager/pages/ListeningForDeviceOnline.ets +++ b/code/DocsSample/CoreFile/UserFile/DevelopingFileManagerApplication/entry/src/main/ets/filemanager/pages/ListeningForDeviceOnline.ets @@ -80,6 +80,20 @@ struct Index { onInit() { this.createFileAccessHelper(); } + // [Start monitor_equipment] + // [Start call_bakc_dir1] + // 提供监听回调方法 + callBackDir1 = (notifyMessageDir: fileAccess.NotifyMessage) => { + if (notifyMessageDir != undefined) { + Logger.info('NotifyType: ' + notifyMessageDir.type + 'NotifyUri:' + notifyMessageDir.uris[0]); + // [StartExclude call_bakc_dir1] + this.result = 'Monitoring succeeded'; // 更新 result 状态 + // [EndExclude call_bakc_dir1] + } else { + Logger.error('notifyMessageDir is undefined'); + } + } + // [End call_bakc_dir1] createFileAccessHelper(): void { try { @@ -93,16 +107,6 @@ struct Index { } } - // 提供监听回调方法 - callBackDir1 = (notifyMessageDir: fileAccess.NotifyMessage) => { - if (notifyMessageDir != undefined) { - Logger.info('NotifyType: ' + notifyMessageDir.type + 'NotifyUri:' + notifyMessageDir.uris[0]); - this.result = 'Monitoring succeeded'; // 更新 result 状态 - } else { - Logger.error('notifyMessageDir is undefined'); - } - } - // 注册监听设备 registerObserver() { try { @@ -124,4 +128,5 @@ struct Index { Logger.error('unregisterObserver failed, errCode:' + error.code + ', errMessage:' + error.message); } } + // [Start monitor_equipment] } \ No newline at end of file diff --git a/code/DocsSample/CoreFile/UserFile/DevelopingFileManagerApplication/entry/src/main/module.json5 b/code/DocsSample/CoreFile/UserFile/DevelopingFileManagerApplication/entry/src/main/module.json5 index 16d83306bb..6ca4e3e8b9 100644 --- a/code/DocsSample/CoreFile/UserFile/DevelopingFileManagerApplication/entry/src/main/module.json5 +++ b/code/DocsSample/CoreFile/UserFile/DevelopingFileManagerApplication/entry/src/main/module.json5 @@ -62,27 +62,29 @@ ] } ], + // [Start request_permission_file_manager] "requestPermissions": [ { - "name": "ohos.permission.FILE_ACCESS_MANAGER", // 声明要申请的权限 - "reason": "$string:reason_MICROPHONE", // 申请该权限的原因 + "name": "ohos.permission.FILE_ACCESS_MANAGER", // 声明要申请的权限 + "reason": "$string:reason_MICROPHONE", // 申请该权限的原因 "usedScene": { "abilities": [ - "FormAbility" // 使用权限的UIAbility或者ExtensionAbility组件的名称。 + "FormAbility" // 使用权限的UIAbility或者ExtensionAbility组件的名称。 ], - "when":"always" // 调用时机 always:始终 inuse:使用时(在前台) + "when":"always" // 调用时机 always:始终 inuse:使用时(在前台) } }, { - "name": "ohos.permission.GET_BUNDLE_INFO_PRIVILEGED", // 声明要申请的权限 - "reason": "$string:reason_MICROPHONE", // 申请该权限的原因 + "name": "ohos.permission.GET_BUNDLE_INFO_PRIVILEGED", // 声明要申请的权限 + "reason": "$string:reason_MICROPHONE", // 申请该权限的原因 "usedScene": { "abilities": [ - "FormAbility" // 使用权限的UIAbility或者ExtensionAbility组件的名称。 + "FormAbility" // 使用权限的UIAbility或者ExtensionAbility组件的名称。 ], - "when":"always" // 调用时机 always:始终 inuse:使用时(在前台) + "when":"always" // 调用时机 always:始终 inuse:使用时(在前台) } } ] + // [End request_permission_file_manager] } } \ No newline at end of file diff --git a/code/DocsSample/CoreFile/UserFile/FileUriDevelopment_C/build-profile.json5 b/code/DocsSample/CoreFile/UserFile/FileUriDevelopment_C/build-profile.json5 index 6ba10a5d9b..099dfbac6e 100644 --- a/code/DocsSample/CoreFile/UserFile/FileUriDevelopment_C/build-profile.json5 +++ b/code/DocsSample/CoreFile/UserFile/FileUriDevelopment_C/build-profile.json5 @@ -15,8 +15,6 @@ { "app": { - "signingConfigs": [ - ], "products": [ { "name": "default", diff --git a/code/DocsSample/CoreFile/UserFile/FileUriDevelopment_C/entry/src/main/cpp/napi_init.cpp b/code/DocsSample/CoreFile/UserFile/FileUriDevelopment_C/entry/src/main/cpp/napi_init.cpp index 6f84f1a399..ff8a2d2363 100644 --- a/code/DocsSample/CoreFile/UserFile/FileUriDevelopment_C/entry/src/main/cpp/napi_init.cpp +++ b/code/DocsSample/CoreFile/UserFile/FileUriDevelopment_C/entry/src/main/cpp/napi_init.cpp @@ -21,8 +21,10 @@ #undef LOG_TAG #define LOG_TAG "Sample_fileUri" +// [Start get_uri_from_path_example] static napi_value NAPI_Global_OH_FileUri_GetUriFromPathExample(napi_env env, napi_callback_info info) -{ +{ + // [StartExclude get_uri_from_path_example] // 参数个数为1 size_t argc = 1; napi_value args[1] = { nullptr }; @@ -31,19 +33,25 @@ static napi_value NAPI_Global_OH_FileUri_GetUriFromPathExample(napi_env env, nap // 获取字符串的长度,初始化字符串长度为0 size_t strLength = 0; napi_get_value_string_utf8(env, args[0], nullptr, 0, &strLength); + // [EndExclude get_uri_from_path_example] // 为 char* uri 分配内存 char *path = new char[strLength + 1]; // +1 for null terminator // 将 JavaScript 字符串复制到 uri + // [StartExclude get_uri_from_path_example] napi_get_value_string_utf8(env, args[0], path, strLength + 1, &strLength); - + // [EndExclude get_uri_from_path_example] unsigned int length = strlen(path); // 输出传入路径字符串 + // [StartExclude get_uri_from_path_example] OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.WatcherType=OnTrigger: %{public}s", path); + // [EndExclude get_uri_from_path_example] char *uriResult = nullptr; FileManagement_ErrCode ret = OH_FileUri_GetUriFromPath(path, length, &uriResult); // 输出结果uri字符串 + // [StartExclude get_uri_from_path_example] OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.WatcherType=OnTrigger: %{public}s", uriResult); napi_value result; + // [EndExclude get_uri_from_path_example] if (ret == 0 && uriResult != nullptr) { // 将C字符串转换为napi_value napi_status status = napi_create_string_utf8(env, uriResult, NAPI_AUTO_LENGTH, &result); @@ -61,8 +69,12 @@ static napi_value NAPI_Global_OH_FileUri_GetUriFromPathExample(napi_env env, nap } return result; } +// [End get_uri_from_path_example] + +// [Start get_path_from_uri_example] static napi_value NAPI_Global_OH_FileUri_GetPathFromUriExample(napi_env env, napi_callback_info info) { + // [StartExclude get_path_from_uri_example] // 参数个数为1 size_t argc = 1; napi_value args[1] = { nullptr }; @@ -73,6 +85,7 @@ static napi_value NAPI_Global_OH_FileUri_GetPathFromUriExample(napi_env env, nap size_t strLength = 0; napi_get_value_string_utf8(env, args[0], nullptr, 0, &strLength); // 为 char* uri 分配内存 + // [EndExclude get_path_from_uri_example] char *uri = new char[strLength + 1]; // +1 for null terminator // 将 JavaScript 字符串复制到 uri napi_get_value_string_utf8(env, args[0], uri, strLength + 1, &strLength); @@ -83,8 +96,10 @@ static napi_value NAPI_Global_OH_FileUri_GetPathFromUriExample(napi_env env, nap char *pathResult = nullptr; FileManagement_ErrCode ret = OH_FileUri_GetPathFromUri(uri, length, &pathResult); // 输出获取路径结果符串 + // [StartExclude get_path_from_uri_example] OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.WatcherType=OnTrigger: %{public}s", pathResult); napi_value result; + // [EndExclude get_path_from_uri_example] if (ret == 0 && pathResult != nullptr) { // 将C字符串转换为napi_value napi_status status = napi_create_string_utf8(env, pathResult, NAPI_AUTO_LENGTH, &result); @@ -102,8 +117,12 @@ static napi_value NAPI_Global_OH_FileUri_GetPathFromUriExample(napi_env env, nap } return result; } +// [End get_path_from_uri_example] + +// [Start get_full_directory_uri] static napi_value NAPI_Global_OH_FileUri_GetFullDirectoryUriExample(napi_env env, napi_callback_info info) { + // [StartExclude get_full_directory_uri] // 参数个数为1 size_t argc = 1; napi_value args[1] = { nullptr }; @@ -114,6 +133,7 @@ static napi_value NAPI_Global_OH_FileUri_GetFullDirectoryUriExample(napi_env env size_t strLength = 0; napi_get_value_string_utf8(env, args[0], nullptr, 0, &strLength); // 为 char* uri 分配内存 + // [EndExclude get_full_directory_uri] char *uri = new char[strLength + 1]; // +1 for null terminator // 将 JavaScript 字符串复制到 uri napi_get_value_string_utf8(env, args[0], uri, strLength + 1, &strLength); @@ -124,8 +144,10 @@ static napi_value NAPI_Global_OH_FileUri_GetFullDirectoryUriExample(napi_env env char *uriResult = nullptr; FileManagement_ErrCode ret = OH_FileUri_GetFullDirectoryUri(uri, length, &uriResult); // 输出所在路径uri字符串 + // [StartExclude get_full_directory_uri] OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.WatcherType=OnTrigger: %{public}s", uriResult); napi_value result = nullptr; + // [EndExclude get_full_directory_uri] if (ret == 0 && uriResult != nullptr) { // 使用napi接口创建一个字符串类型的napi_value来返回正确结果 napi_create_string_utf8(env, uriResult, NAPI_AUTO_LENGTH, &result); @@ -138,8 +160,12 @@ static napi_value NAPI_Global_OH_FileUri_GetFullDirectoryUriExample(napi_env env } return result; } +// [Start get_full_directory_uri] + +// [Start is_valid_uri_example] static napi_value NAPI_Global_OH_FileUri_IsValidUriExample(napi_env env, napi_callback_info info) { + // [StartExclude is_valid_uri_example] // 参数个数为1 size_t argc = 1; napi_value args[1] = { nullptr }; @@ -150,14 +176,15 @@ static napi_value NAPI_Global_OH_FileUri_IsValidUriExample(napi_env env, napi_ca size_t strLength = 0; napi_get_value_string_utf8(env, args[0], nullptr, 0, &strLength); // 为 char* uri 分配内存 + // [EndExclude is_valid_uri_example] char *uri = new char[strLength + 1]; // +1 for null terminator // 将 JavaScript 字符串复制到 uri napi_get_value_string_utf8(env, args[0], uri, strLength + 1, &strLength); - unsigned int length = strlen(uri); // 输出传入uri字符串 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.WatcherType=OnTrigger: %{public}s", uri); bool flags = OH_FileUri_IsValidUri(uri, length); + // [StartExclude is_valid_uri_example] napi_value result; // 将bool值转换为napi_value napi_status status = napi_get_boolean(env, flags, &result); @@ -167,9 +194,14 @@ static napi_value NAPI_Global_OH_FileUri_IsValidUriExample(napi_env env, napi_ca return nullptr; } return result; + // [EndExclude is_valid_uri_example] } +// [End is_valid_uri_example] + +// [Start get_file_name_example] static napi_value NAPI_Global_OH_FileUri_GetFileNameExample(napi_env env, napi_callback_info info) { + // [StartExclude get_file_name_example] // 参数个数为1 size_t argc = 1; napi_value args[1] = { nullptr }; @@ -180,6 +212,7 @@ static napi_value NAPI_Global_OH_FileUri_GetFileNameExample(napi_env env, napi_c size_t strLength = 0; napi_get_value_string_utf8(env, args[0], nullptr, 0, &strLength); // 为 char* uri 分配内存 + // [EndExclude get_file_name_example] char *uri = new char[strLength + 1]; // +1 for null terminator // 将 JavaScript 字符串复制到 uri napi_get_value_string_utf8(env, args[0], uri, strLength + 1, &strLength); @@ -190,8 +223,10 @@ static napi_value NAPI_Global_OH_FileUri_GetFileNameExample(napi_env env, napi_c char *uriResult = nullptr; FileManagement_ErrCode ret = OH_FileUri_GetFileName(uri, length, &uriResult); // 输出获取到的文件名称 + // [StartExclude get_file_name_example] OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.WatcherType=OnTrigger: %{public}s", uriResult); napi_value result; + // [EndExclude get_file_name_example] if (ret == 0 && uriResult != nullptr) { // 将C字符串转换为napi_value napi_status status = napi_create_string_utf8(env, uriResult, NAPI_AUTO_LENGTH, &result); @@ -209,6 +244,8 @@ static napi_value NAPI_Global_OH_FileUri_GetFileNameExample(napi_env env, napi_c } return result; } +// [End get_file_name_example] + EXTERN_C_START static napi_value Init(napi_env env, napi_value exports) { diff --git a/code/DocsSample/CoreFile/UserFile/ManagingExternalStorageDevices/build-profile.json5 b/code/DocsSample/CoreFile/UserFile/ManagingExternalStorageDevices/build-profile.json5 index 6ba10a5d9b..099dfbac6e 100644 --- a/code/DocsSample/CoreFile/UserFile/ManagingExternalStorageDevices/build-profile.json5 +++ b/code/DocsSample/CoreFile/UserFile/ManagingExternalStorageDevices/build-profile.json5 @@ -15,8 +15,6 @@ { "app": { - "signingConfigs": [ - ], "products": [ { "name": "default", diff --git a/code/DocsSample/CoreFile/UserFile/ManagingExternalStorageDevices/entry/src/main/ets/pages/Index.ets b/code/DocsSample/CoreFile/UserFile/ManagingExternalStorageDevices/entry/src/main/ets/pages/Index.ets index 0441b2f395..a710e32bf0 100644 --- a/code/DocsSample/CoreFile/UserFile/ManagingExternalStorageDevices/entry/src/main/ets/pages/Index.ets +++ b/code/DocsSample/CoreFile/UserFile/ManagingExternalStorageDevices/entry/src/main/ets/pages/Index.ets @@ -13,13 +13,14 @@ * limitations under the License. */ +// [Start subscribe_events_1] import { BusinessError } from '@kit.BasicServicesKit'; import { commonEventManager } from '@kit.BasicServicesKit'; import { volumeManager } from '@kit.CoreFileKit'; import Logger from '../common/Logger'; let subscriber: commonEventManager.CommonEventSubscriber; - +// [End subscribe_events_1] @Entry @Component struct Index { @@ -85,6 +86,7 @@ struct Index { .backgroundColor($r('app.color.lightGrayColor')) // 设置背景颜色为浅灰色 } + // [Start subscribe_events_2] async subscribeToEvents() { Logger.info('subscribeToEvents() begin'); const subscribeInfo: commonEventManager.CommonEventSubscribeInfo = { @@ -103,18 +105,24 @@ struct Index { Logger.error('Failed to create subscriber: ' + JSON.stringify(error)); } } + // [End subscribe_events_2] + // [Start subscribe_events_3] receiveBroadcastNotifications() { + // [StartExclude subscribe_events_3] Logger.info('receiveBroadcastNotifications() begin'); if (subscriber === undefined) { Logger.error('Subscriber is not defined. Please subscribe to events first.'); return; } + // [EndExclude subscribe_events_3] commonEventManager.subscribe(subscriber, (err: BusinessError, data: commonEventManager.CommonEventData) => { + // [StartExclude subscribe_events_3] if (err) { Logger.error('Subscription failed: ' + JSON.stringify(err)); return; } + // [EndExclude subscribe_events_3] if (data.event === 'usual.event.data.VOLUME_MOUNTED' && data.parameters !== undefined) { let volId: string = data.parameters.id; volumeManager.getVolumeById(volId, (error: BusinessError, vol: volumeManager.Volume) => { @@ -122,10 +130,13 @@ struct Index { Logger.error('volumeManager getVolumeById failed for ' + JSON.stringify(error)); } else { Logger.info('volumeManager getVolumeById successfully, the volume state is ' + vol.state); + // [StartExclude subscribe_events_3] this.message = 'Successfully obtained volume device information'; + // [EndExclude subscribe_events_3] } }); } }); } + // [End subscribe_events_3] } \ No newline at end of file diff --git a/code/DocsSample/CoreFile/UserFile/SavingUserFiles/build-profile.json5 b/code/DocsSample/CoreFile/UserFile/SavingUserFiles/build-profile.json5 index 6ba10a5d9b..099dfbac6e 100644 --- a/code/DocsSample/CoreFile/UserFile/SavingUserFiles/build-profile.json5 +++ b/code/DocsSample/CoreFile/UserFile/SavingUserFiles/build-profile.json5 @@ -15,8 +15,6 @@ { "app": { - "signingConfigs": [ - ], "products": [ { "name": "default", diff --git a/code/DocsSample/CoreFile/UserFile/SavingUserFiles/entry/src/main/ets/pages/Index.ets b/code/DocsSample/CoreFile/UserFile/SavingUserFiles/entry/src/main/ets/pages/Index.ets index 6f3cb496d8..e051cf285c 100644 --- a/code/DocsSample/CoreFile/UserFile/SavingUserFiles/entry/src/main/ets/pages/Index.ets +++ b/code/DocsSample/CoreFile/UserFile/SavingUserFiles/entry/src/main/ets/pages/Index.ets @@ -13,10 +13,12 @@ * limitations under the License. */ +// [Start import_interface_fileio] import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; import { fileIo as fs, picker } from '@kit.CoreFileKit'; import Logger from '..//common//Logger'; +// [End import_interface_fileio] // 确保 getContext(this) 返回结果为 UIAbilityContext let context = getContext(this) as common.Context; @@ -109,29 +111,40 @@ struct Index { } saveDocumentFile() { + // [Start document_save_options] const documentSaveOptions = new picker.DocumentSaveOptions(); documentSaveOptions.newFileNames = ['DocumentViewPicker01.txt']; documentSaveOptions.fileSuffixChoices = [resourceToString($r('app.string.document')), '.pdf']; + // [End document_save_options] + // [Start save_file_picker] const context = getContext(this) as common.Context; const documentViewPicker = new picker.DocumentViewPicker(context); documentViewPicker.save(documentSaveOptions).then((documentSaveResult: string[]) => { this.uris = documentSaveResult; Logger.info('documentViewPicker.save to file succeed and uris are:' + this.uris); + // [StartExclude save_file_picker] if (this.uris.length > 0) { this.writeDocumentFile(this.uris[0]); } + // [EndExclude save_file_picker] }).catch((err: BusinessError) => { Logger.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`); }); + // [End save_file_picker] } writeDocumentFile(uri: string) { + // [Start document_open_mode] let file = fs.openSync(uri, fs.OpenMode.READ_WRITE); Logger.info('file fd: ' + file.fd); + // [End document_open_mode] + + // [Start document_writesync] let writeLen: number = fs.writeSync(file.fd, 'hello, world'); Logger.info('write data to file succeed and size is:' + writeLen); fs.closeSync(file); + // [End document_writesync] } selectDocumentFiles() { @@ -160,8 +173,12 @@ struct Index { } saveAudioFile() { + // [Start audio_save_options] const audioSaveOptions = new picker.AudioSaveOptions(); audioSaveOptions.newFileNames = ['AudioViewPicker03.mp3']; // 保存文件名(可选) + // [End audio_save_options] + + // [Start audio_save_file] const context = getContext(this) as common.Context; const audioViewPicker = new picker.AudioViewPicker(context); audioViewPicker.save(audioSaveOptions).then((audioSelectResult: string[]) => { @@ -171,6 +188,7 @@ struct Index { }).catch((err: BusinessError) => { Logger.error(`Invoke audioViewPicker.save failed, code is ${err.code}, message is ${err.message}`); }); + // [Start audio_save_file] } writeAudioFile() { @@ -178,11 +196,16 @@ struct Index { Logger.error('URI is empty, cannot write file'); return; } + // [Start audio_open_mode] let file = fs.openSync(this.uri, fs.OpenMode.READ_WRITE); Logger.info('file fd: ' + file.fd); + // [End audio_open_mode] + + // [Start audio_write_sync] let writeLen = fs.writeSync(file.fd, 'hello, world'); Logger.info('write data to file succeed and size is:' + writeLen); fs.closeSync(file); + // [End audio_write_sync] this.result = 'Successfully saved audio files'; } } \ No newline at end of file diff --git a/code/DocsSample/CoreFile/UserFile/SelectingUserFiles/build-profile.json5 b/code/DocsSample/CoreFile/UserFile/SelectingUserFiles/build-profile.json5 index 6ba10a5d9b..099dfbac6e 100644 --- a/code/DocsSample/CoreFile/UserFile/SelectingUserFiles/build-profile.json5 +++ b/code/DocsSample/CoreFile/UserFile/SelectingUserFiles/build-profile.json5 @@ -15,8 +15,6 @@ { "app": { - "signingConfigs": [ - ], "products": [ { "name": "default", diff --git a/code/DocsSample/CoreFile/UserFile/SelectingUserFiles/entry/src/main/ets/pages/Index.ets b/code/DocsSample/CoreFile/UserFile/SelectingUserFiles/entry/src/main/ets/pages/Index.ets index 2d6e9b3977..9d5ce02dba 100644 --- a/code/DocsSample/CoreFile/UserFile/SelectingUserFiles/entry/src/main/ets/pages/Index.ets +++ b/code/DocsSample/CoreFile/UserFile/SelectingUserFiles/entry/src/main/ets/pages/Index.ets @@ -13,10 +13,12 @@ * limitations under the License. */ +// [Start import_interface_file] import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; import { fileAccess, fileIo as fs, picker } from '@kit.CoreFileKit'; import Logger from '../common/Logger'; +// [End import_interface_file] let context = getContext(this) as common.Context; @@ -125,58 +127,83 @@ struct Index { } selectDocumentFiles() { + // [Start create_document_select_option] const documentSelectOptions = new picker.DocumentSelectOptions(); + // [End create_document_select_option] + // [Start picker_select] const context = getContext(this) as common.Context; const documentViewPicker = new picker.DocumentViewPicker(context); documentViewPicker.select(documentSelectOptions).then((documentSelectResult: string[]) => { this.documentUris = documentSelectResult; Logger.info('documentViewPicker.select to file succeed and uris are:' + this.documentUris); + // [StartExclude picker_select] if (this.documentUris.length > 0) { this.readDocumentFile(this.documentUris[0]); } + // [EndExclude picker_select] }).catch((err: BusinessError) => { Logger.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`); }); + // [End picker_select] } readDocumentFile(uri: string) { + // [Start document_read_only] let file = fs.openSync(uri, fs.OpenMode.READ_ONLY); Logger.info('file fd: ' + file.fd); + // [End document_read_only] + + // [Start document_fs_read_sync] let buffer = new ArrayBuffer(4096); // 分配一个大小为4096字节的缓冲区 let readLen = fs.readSync(file.fd, buffer); // 读取文件内容 Logger.info('readSync data to file succeed and buffer size is:' + readLen); this.result = 'Read Success'; fs.closeSync(file); + // [Start document_fs_read_sync] } + // [Start audio_view_picker] async selectAudioFile() { + // [Start audio_select_option] const audioSelectOptions = new picker.AudioSelectOptions(); + // [End audio_select_option] const audioViewPicker = new picker.AudioViewPicker(context); try { const audioSelectResult: string[] = await audioViewPicker.select(audioSelectOptions); this.audioUris = audioSelectResult[0]; Logger.info('audioViewPicker.select to file succeed and uri is:' + this.audioUris); + // [StartExclude audio_view_picker] this.fileContent = 'Select Success'; this.readAudioFile(this.audioUris); + // [EndExclude audio_view_picker] } catch (err) { const error: BusinessError = err as BusinessError; Logger.error(`Invoke audioViewPicker.select failed, code is ${error.code}, message is ${error.message}`); } } + // [Start audio_view_picker] readAudioFile(uri: string) { try { + // [Start openmode_read_only] const file = fs.openSync(uri, fs.OpenMode.READ_ONLY); Logger.info('file fd: ' + file.fd); + // [Start openmode_read_only] + + // [Start fs_read_sync] const buffer = new ArrayBuffer(4096); // 分配一个大小为4096字节的缓冲区 const readLen = fs.readSync(file.fd, buffer); // 读取文件内容 Logger.info('readSync data to file succeed and buffer size is:' + readLen); + // [StartExclude fs_read_sync] this.fileContent = `Read ${readLen} bytes from file.`; // 显示读取的字节数 + // [EndExclude fs_read_sync] fs.closeSync(file); + // [End fs_read_sync] } catch (err) { const error: BusinessError = err as BusinessError; Logger.error(`Failed to read file, code is ${error.code}, message is ${error.message}`); } } + } \ No newline at end of file diff --git a/code/DocsSample/CoreFile/UserFile/UserFileURI/build-profile.json5 b/code/DocsSample/CoreFile/UserFile/UserFileURI/build-profile.json5 index 62fb1775eb..0fa83c0da1 100644 --- a/code/DocsSample/CoreFile/UserFile/UserFileURI/build-profile.json5 +++ b/code/DocsSample/CoreFile/UserFile/UserFileURI/build-profile.json5 @@ -15,8 +15,6 @@ { "app": { - "signingConfigs": [ - ], "products": [ { "name": "default", diff --git a/code/DocsSample/CoreFile/UserFile/UserFileURI/entry/src/main/ets/pages/Index.ets b/code/DocsSample/CoreFile/UserFile/UserFileURI/entry/src/main/ets/pages/Index.ets index b029c230a2..5ea7004139 100644 --- a/code/DocsSample/CoreFile/UserFile/UserFileURI/entry/src/main/ets/pages/Index.ets +++ b/code/DocsSample/CoreFile/UserFile/UserFileURI/entry/src/main/ets/pages/Index.ets @@ -13,6 +13,8 @@ * limitations under the License. */ +// [Start import_user_fileAccess] +// [Start import_get_uri_assets] import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; import { dataSharePredicates } from '@kit.ArkData'; @@ -23,9 +25,12 @@ import Logger from '../common/Logger'; // context 是EntryAbility 传过来的context let context = getContext(this) as common.UIAbilityContext; +// [End import_user_fileAccess] + // 定义一个uri数组,用于接收PhotoViewPicker选择图片返回的uri let uris: string[] = []; +// [StartExclude import_get_uri_assets] async function getFileAccessAbilityInfo() { let wantInfos: Want[] = []; try { @@ -36,7 +41,9 @@ async function getFileAccessAbilityInfo() { Logger.error('getFileAccessAbilityInfo failed, errCode:' + error.code + ', errMessage:' + error.message); } } +// [EndExclude import_get_uri_assets] +// [Start ] // 调用PhotoViewPicker.select选择图片 async function photoPickerGetUri() { try { @@ -87,15 +94,18 @@ async function uriGetAssets(): Promise { console.error('getThumbnail fail', err); } }); + // [StartExclude import_get_uri_assets] if (uris.length !== 0 && asset !== null) { return 'ReadMediaUriSuccess'; } + // [EndExclude import_get_uri_assets] } catch (error) { console.error('uriGetAssets failed with err: ' + JSON.stringify(error)); return 'ReadMediaUriFail'; } return 'ReadMediaUriFail'; } +// [End import_get_uri_assets] @Entry @Component @@ -204,6 +214,7 @@ struct Index { .backgroundColor($r('app.color.lightGrayColor')) // 背景颜色为浅灰色 } + // [Start function_example] async documentURIExample() { let fileAccessHelper: fileAccess.FileAccessHelper; // wantInfos 从getFileAccessAbilityInfo()获取 @@ -244,7 +255,9 @@ struct Index { Logger.error('createFileAccessHelper failed, errCode:' + error.code + ', errMessage:' + error.message); } } - + // [Start function_example] + + // [Start copy_file_uri_example ] async copyingFileByUriExample() { let fileAccessHelper: fileAccess.FileAccessHelper; // wantInfos 从getFileAccessAbilityInfo()获取 @@ -286,6 +299,7 @@ struct Index { Logger.error('createFileAccessHelper failed, errCode:' + error.code + ', errMessage:' + error.message); } } + // [End copy_file_uri_example] selectDocumentFiles() { const documentSelectOptions = new picker.DocumentSelectOptions(); -- Gitee