diff --git a/CoreFileKit/AppScope/app.json5 b/CoreFileKit/AppScope/app.json5 new file mode 100644 index 0000000000000000000000000000000000000000..82a9586484a54636236415a786742a7168ebeff2 --- /dev/null +++ b/CoreFileKit/AppScope/app.json5 @@ -0,0 +1,10 @@ +{ + "app": { + "bundleName": "com.example.corefilekit", + "vendor": "example", + "versionCode": 1000000, + "versionName": "1.0.0", + "icon": "$media:layered_image", + "label": "$string:app_name" + } +} diff --git a/CoreFileKit/AppScope/resources/base/element/string.json b/CoreFileKit/AppScope/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..62fcc31f4405e696575142c0ea566d1a62fc97ec --- /dev/null +++ b/CoreFileKit/AppScope/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "app_name", + "value": "CoreFileKit" + } + ] +} diff --git a/CoreFileKit/AppScope/resources/base/media/background.png b/CoreFileKit/AppScope/resources/base/media/background.png new file mode 100644 index 0000000000000000000000000000000000000000..923f2b3f27e915d6871871deea0420eb45ce102f Binary files /dev/null and b/CoreFileKit/AppScope/resources/base/media/background.png differ diff --git a/CoreFileKit/AppScope/resources/base/media/foreground.png b/CoreFileKit/AppScope/resources/base/media/foreground.png new file mode 100644 index 0000000000000000000000000000000000000000..97014d3e10e5ff511409c378cd4255713aecd85f Binary files /dev/null and b/CoreFileKit/AppScope/resources/base/media/foreground.png differ diff --git a/CoreFileKit/AppScope/resources/base/media/layered_image.json b/CoreFileKit/AppScope/resources/base/media/layered_image.json new file mode 100644 index 0000000000000000000000000000000000000000..fb49920440fb4d246c82f9ada275e26123a2136a --- /dev/null +++ b/CoreFileKit/AppScope/resources/base/media/layered_image.json @@ -0,0 +1,7 @@ +{ + "layered-image": + { + "background" : "$media:background", + "foreground" : "$media:foreground" + } +} \ No newline at end of file diff --git a/CoreFileKit/build-profile.json5 b/CoreFileKit/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..03ac3a3ae9dd397844173066e5d5ee21b49455a1 --- /dev/null +++ b/CoreFileKit/build-profile.json5 @@ -0,0 +1,41 @@ +{ + "app": { + "signingConfigs": [], + "products": [ + { + "name": "default", + "signingConfig": "default", + "compatibleSdkVersion": "5.0.4(16)", + "runtimeOS": "HarmonyOS", + "buildOption": { + "strictMode": { + "caseSensitiveCheck": true, + "useNormalizedOHMUrl": true + } + } + } + ], + "buildModeSet": [ + { + "name": "debug", + }, + { + "name": "release" + } + ] + }, + "modules": [ + { + "name": "entry", + "srcPath": "./entry", + "targets": [ + { + "name": "default", + "applyToProducts": [ + "default" + ] + } + ] + } + ] +} \ No newline at end of file diff --git a/CoreFileKit/code-linter.json5 b/CoreFileKit/code-linter.json5 new file mode 100644 index 0000000000000000000000000000000000000000..073990fa45394e1f8e85d85418ee60a8953f9b99 --- /dev/null +++ b/CoreFileKit/code-linter.json5 @@ -0,0 +1,32 @@ +{ + "files": [ + "**/*.ets" + ], + "ignore": [ + "**/src/ohosTest/**/*", + "**/src/test/**/*", + "**/src/mock/**/*", + "**/node_modules/**/*", + "**/oh_modules/**/*", + "**/build/**/*", + "**/.preview/**/*" + ], + "ruleSet": [ + "plugin:@performance/recommended", + "plugin:@typescript-eslint/recommended" + ], + "rules": { + "@security/no-unsafe-aes": "error", + "@security/no-unsafe-hash": "error", + "@security/no-unsafe-mac": "warn", + "@security/no-unsafe-dh": "error", + "@security/no-unsafe-dsa": "error", + "@security/no-unsafe-ecdsa": "error", + "@security/no-unsafe-rsa-encrypt": "error", + "@security/no-unsafe-rsa-sign": "error", + "@security/no-unsafe-rsa-key": "error", + "@security/no-unsafe-dsa-key": "error", + "@security/no-unsafe-dh-key": "error", + "@security/no-unsafe-3des": "error" + } +} \ No newline at end of file diff --git a/CoreFileKit/entry/build-profile.json5 b/CoreFileKit/entry/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..4d611879c7913fb0610c686e2399258ab3a6dad1 --- /dev/null +++ b/CoreFileKit/entry/build-profile.json5 @@ -0,0 +1,28 @@ +{ + "apiType": "stageMode", + "buildOption": { + }, + "buildOptionSet": [ + { + "name": "release", + "arkOptions": { + "obfuscation": { + "ruleOptions": { + "enable": false, + "files": [ + "./obfuscation-rules.txt" + ] + } + } + } + }, + ], + "targets": [ + { + "name": "default" + }, + { + "name": "ohosTest", + } + ] +} \ No newline at end of file diff --git a/CoreFileKit/entry/hvigorfile.ts b/CoreFileKit/entry/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..c6edcd90486dd5a853cf7d34c8647f08414ca7a3 --- /dev/null +++ b/CoreFileKit/entry/hvigorfile.ts @@ -0,0 +1,6 @@ +import { hapTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins:[] /* Custom plugin to extend the functionality of Hvigor. */ +} diff --git a/CoreFileKit/entry/obfuscation-rules.txt b/CoreFileKit/entry/obfuscation-rules.txt new file mode 100644 index 0000000000000000000000000000000000000000..272efb6ca3f240859091bbbfc7c5802d52793b0b --- /dev/null +++ b/CoreFileKit/entry/obfuscation-rules.txt @@ -0,0 +1,23 @@ +# Define project specific obfuscation rules here. +# You can include the obfuscation configuration files in the current module's build-profile.json5. +# +# For more details, see +# https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/source-obfuscation-V5 + +# Obfuscation options: +# -disable-obfuscation: disable all obfuscations +# -enable-property-obfuscation: obfuscate the property names +# -enable-toplevel-obfuscation: obfuscate the names in the global scope +# -compact: remove unnecessary blank spaces and all line feeds +# -remove-log: remove all console.* statements +# -print-namecache: print the name cache that contains the mapping from the old names to new names +# -apply-namecache: reuse the given cache file + +# Keep options: +# -keep-property-name: specifies property names that you want to keep +# -keep-global-name: specifies names that you want to keep in the global scope + +-enable-property-obfuscation +-enable-toplevel-obfuscation +-enable-filename-obfuscation +-enable-export-obfuscation \ No newline at end of file diff --git a/CoreFileKit/entry/oh-package.json5 b/CoreFileKit/entry/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..248c3b7541a589682a250f86a6d3ecf7414d2d6a --- /dev/null +++ b/CoreFileKit/entry/oh-package.json5 @@ -0,0 +1,10 @@ +{ + "name": "entry", + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "", + "author": "", + "license": "", + "dependencies": {} +} + diff --git a/CoreFileKit/entry/src/main/ets/entryability/EntryAbility.ets b/CoreFileKit/entry/src/main/ets/entryability/EntryAbility.ets new file mode 100644 index 0000000000000000000000000000000000000000..508880af8c33aa838016d1cd4b2c68be2f447540 --- /dev/null +++ b/CoreFileKit/entry/src/main/ets/entryability/EntryAbility.ets @@ -0,0 +1,44 @@ +import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; +import { window } from '@kit.ArkUI'; + +const DOMAIN = 0x0000; + +export default class EntryAbility extends UIAbility { + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { + this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET); + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate'); + } + + onDestroy(): void { + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy'); + } + + onWindowStageCreate(windowStage: window.WindowStage): void { + // Main window is created, set main page for this ability + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); + + windowStage.loadContent('pages/Index', (err) => { + if (err.code) { + hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err)); + return; + } + hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.'); + }); + } + + onWindowStageDestroy(): void { + // Main window is destroyed, release UI related resources + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy'); + } + + onForeground(): void { + // Ability has brought to foreground + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground'); + } + + onBackground(): void { + // Ability has back to background + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground'); + } +} \ No newline at end of file diff --git a/CoreFileKit/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets b/CoreFileKit/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets new file mode 100644 index 0000000000000000000000000000000000000000..8e4de99282050bad799ac892eb85ac5449364a51 --- /dev/null +++ b/CoreFileKit/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets @@ -0,0 +1,16 @@ +import { hilog } from '@kit.PerformanceAnalysisKit'; +import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit'; + +const DOMAIN = 0x0000; + +export default class EntryBackupAbility extends BackupExtensionAbility { + async onBackup() { + hilog.info(DOMAIN, 'testTag', 'onBackup ok'); + await Promise.resolve(); + } + + async onRestore(bundleVersion: BundleVersion) { + hilog.info(DOMAIN, 'testTag', 'onRestore ok %{public}s', JSON.stringify(bundleVersion)); + await Promise.resolve(); + } +} \ No newline at end of file diff --git a/CoreFileKit/entry/src/main/ets/pages/CacheSizeAndCleanupAPI.ets b/CoreFileKit/entry/src/main/ets/pages/CacheSizeAndCleanupAPI.ets new file mode 100644 index 0000000000000000000000000000000000000000..c845ac46ef5c4bc46bdf30b358ad1e4f2c327a3c --- /dev/null +++ b/CoreFileKit/entry/src/main/ets/pages/CacheSizeAndCleanupAPI.ets @@ -0,0 +1,97 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:怎么获取应用已使用的缓存大小,如何使用API清理缓存 +*/ + +// DocsCode 1 +import { fileIo, storageStatistics } from '@kit.CoreFileKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +@Entry +@Component +struct ClearCache { + // 在缓存中创建一个文件 + writeFile() { + let filePath = this.getUIContext().getHostContext()!.cacheDir + '/test.txt'; + let fileStream = fileIo.createStreamSync(filePath, 'w+'); + fileStream.writeSync('1145141919810'); + fileStream.close(); + } + + // 获取应用数据空间大小 + getCache() { + storageStatistics.getCurrentBundleStats((error: BusinessError, bundleStats: storageStatistics.BundleStats) => { + if (error) { + console.error('getCurrentBundleStats failed with error:' + JSON.stringify(error)); + } else { + console.info('getCurrentBundleStats successfully:' + JSON.stringify(bundleStats)); + console.info('appsize :' + bundleStats.appSize); + console.info('cacheSize :' + bundleStats.cacheSize); + console.info('dataSize :' + bundleStats.dataSize); + } + }); + } + + // 清理缓存 + clearCache() { + let cacheDir = this.getUIContext().getHostContext()!.cacheDir; + console.info(cacheDir); + + fileIo.listFile(cacheDir).then((filenames) => { + for (let i = 0; i < filenames.length; i++) { + let dirPath = cacheDir + '/' + filenames[i]; + console.log(dirPath); + // 判断是否为文件夹 + let isDirectory: boolean = false; + try { + isDirectory = fileIo.statSync(dirPath).isDirectory(); + } catch (e) { + console.error(JSON.stringify(e)); + } + + if (isDirectory) { + fileIo.rmdirSync(dirPath); + } else { + fileIo.unlink(dirPath).then(() => { + console.info('remove file succeed'); + }).catch((err: Error) => { + console.error('remove file failed with error message: ' + err.message); + }); + } + } + + }) + } + + build() { + Column() { + Button('向缓存写入数据') + .onClick(() => { + this.writeFile(); + }) + Button('获取系统缓存大小') + .onClick(() => { + this.getCache(); + }) + Button('点击清理缓存') + .onClick(() => { + this.clearCache(); + }) + } + } +} +// DocsCode 1 \ No newline at end of file diff --git a/CoreFileKit/entry/src/main/ets/pages/CheckStorageSpace.ets b/CoreFileKit/entry/src/main/ets/pages/CheckStorageSpace.ets new file mode 100644 index 0000000000000000000000000000000000000000..e8ddc26c20e6d9bcbf3fec56c131cc24f87c3dd5 --- /dev/null +++ b/CoreFileKit/entry/src/main/ets/pages/CheckStorageSpace.ets @@ -0,0 +1,51 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:获取指定文件系统的剩余空间大小 +*/ + +// DocsCode 1 +import { BusinessError } from '@kit.BasicServicesKit'; +import { statfs } from '@kit.CoreFileKit'; + +@Entry +@Component +struct GetFileSpace { + build() { + Column() { + Button('获取系统空间大小') + .onClick(() => { + let context = this.getUIContext().getHostContext(); + let path = context!.filesDir; + + //获取指定文件系统总字节数 + statfs.getTotalSize(path).then((number: number) => { + console.info('getTotalSize succeed, Size: ' + number); + }).catch((err: BusinessError) => { + console.error('getTotalSize failed with error message: ' + err.message + ', error code: ' + err.code); + }); + + //获取指定文件系统空闲字节数 + statfs.getFreeSize(path).then((number: number) => { + console.info('getFreeSize succeed, Size: ' + number); + }).catch((err: BusinessError) => { + console.error('getFreeSize failed with error message: ' + err.message + ', error code: ' + err.code); + }); + }) + } + } +} +// DocsCode 1 \ No newline at end of file diff --git a/CoreFileKit/entry/src/main/ets/pages/CreateTempFile.ets b/CoreFileKit/entry/src/main/ets/pages/CreateTempFile.ets new file mode 100644 index 0000000000000000000000000000000000000000..f1f0522e6b00e2c19849c3f1ceb40e2b5433ee75 --- /dev/null +++ b/CoreFileKit/entry/src/main/ets/pages/CreateTempFile.ets @@ -0,0 +1,69 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何创建临时文件 +*/ + +// DocsCode 1 +import { fileIo as fs, ReadOptions } from '@kit.CoreFileKit'; +import { common } from '@kit.AbilityKit'; +import { buffer } from '@kit.ArkTS'; + +@Entry +@Component +struct CreateFileDemo { + @State message: string = 'Hello World'; + @State writeStr: string = 'write content'; + @State readStr: string = 'read content'; + + build() { + Column() { + Text(this.message) + Button(this.writeStr) + .margin({ top: 15, bottom: 15 }) + .onClick(() => { + let context = this.getUIContext().getHostContext(); + let filesDir = context!.tempDir; + let file = fs.openSync(filesDir + 'test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + // 写入一段内容至文件 + fs.writeSync(file.fd, 'Try to write str.'); + console.info('str has been written'); + // 关闭文件 + fs.closeSync(file); + }) + Button(this.readStr) + .onClick(() => { + let context = this.getUIContext().getHostContext(); + let filesDir = context!.tempDir; + let file = fs.openSync(filesDir + 'test.txt', fs.OpenMode.READ_WRITE); + // 从文件读取一段内容 + let arrayBuffer = new ArrayBuffer(1024); + let readOptions: ReadOptions = { + offset: 0, + length: arrayBuffer.byteLength + }; + let readLen = fs.readSync(file.fd, arrayBuffer, readOptions); + let buf = buffer.from(arrayBuffer, 0, readLen); + this.message = buf.toString(); + // 关闭文件 + fs.closeSync(file); + }) + } + .height('100%') + .width('100%') + } +} +// DocsCode 1 \ No newline at end of file diff --git a/CoreFileKit/entry/src/main/ets/pages/FileContentParser.ets b/CoreFileKit/entry/src/main/ets/pages/FileContentParser.ets new file mode 100644 index 0000000000000000000000000000000000000000..47c11a810659b5c3a33859002ae2ef675bf0a730 --- /dev/null +++ b/CoreFileKit/entry/src/main/ets/pages/FileContentParser.ets @@ -0,0 +1,62 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何读取指定文件内容,并转为具体对象 +*/ + +// DocsCode 1 +import { Context } from '@kit.AbilityKit'; +import { buffer } from '@kit.ArkTS'; + +@Entry +@Component +struct Index { + private context: Context | undefined = this.getUIContext().getHostContext(); + private str: string = ''; + + getRawFile(): ESObject { + //调用getRawFileContent接口获取json文件内容,并读为string + this.getUIContext().getHostContext()!.resourceManager.getRawFileContent('test.json', (err, data) => { + try { + this.str = buffer.from(data.buffer).toString(); + console.info(JSON.stringify(this.str)); + } catch (e) { + console.info(JSON.stringify(e)); + } + }) + //也可以调用getRawFileContentSync接口获取json文件内容,并读为string + try { + let data: Uint8Array = this.context!.resourceManager.getRawFileContentSync('test.json'); + this.str = buffer.from(data.buffer).toString(); + } catch (e) { + console.info(JSON.stringify(e)); + } + // string转为ESObject + let obj: ESObject = JSON.parse(this.str); + console.info('ESObject', JSON.stringify(obj)); + return obj; + } + + build() { + Column() { + Button('get') + .onClick(() => { + this.getRawFile(); + }) + }.width('100%') + } +} +// DocsCode 1 \ No newline at end of file diff --git a/CoreFileKit/entry/src/main/ets/pages/GetRawfile.ets b/CoreFileKit/entry/src/main/ets/pages/GetRawfile.ets new file mode 100644 index 0000000000000000000000000000000000000000..c826f0497653ad082599a784adbe068cf154c242 --- /dev/null +++ b/CoreFileKit/entry/src/main/ets/pages/GetRawfile.ets @@ -0,0 +1,55 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何获取到 resources下rawfile 的文件 +*/ + +// DocsCode 1 +import { fileIo } from '@kit.CoreFileKit'; + +@Component +export struct GetRawfile { + @State message: string = 'Hello World'; + + aboutToAppear(): void { + getContext(this).resourceManager.getRawFileContent('test.txt', (_err, value) => { + let myBuffer: ArrayBufferLike = value.buffer; + let context = this.getUIContext().getHostContext(); //沙箱路径 + let filePath = context!.filesDir + '/test.txt'; + console.info('testTag-filePath:' + filePath); + let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); + let writeLen = fileIo.writeSync(file.fd, myBuffer); + console.info('testTag-write data to file succeed and size is:' + writeLen); + fileIo.closeSync(file); + }); + } + + build() { + RelativeContainer() { + Text(this.message) + .id('RawfileHelloWorld') + .fontSize(50) + .fontWeight(FontWeight.Bold) + .alignRules({ + center: { anchor: '__container__', align: VerticalAlign.Center }, + middle: { anchor: '__container__', align: HorizontalAlign.Center } + }) + } + .height('100%') + .width('100%') + } +} +// DocsCode 1 \ No newline at end of file diff --git a/CoreFileKit/entry/src/main/ets/pages/HandleFileEncodingProblem.ets b/CoreFileKit/entry/src/main/ets/pages/HandleFileEncodingProblem.ets new file mode 100644 index 0000000000000000000000000000000000000000..7a09f947d6bc73b2ecfa607ad7f8ee37ed0c3350 --- /dev/null +++ b/CoreFileKit/entry/src/main/ets/pages/HandleFileEncodingProblem.ets @@ -0,0 +1,41 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何解决文件的中文乱码问题 +*/ + +// DocsCode 1 +import { util } from '@kit.ArkTS'; +import { fileIo } from '@kit.CoreFileKit'; + +// 工具类中:在EntryAbility中获取Context后保存至AppStorage,然后在工具类中使用AppStorage获取 +let context = AppStorage.get("context") as UIContext; +// 创建一个文件写入中文字符 +let filePath = context.getHostContext()!.filesDir + "/test0.txt"; +let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); +// 写入一段内容至文件 +let writeLen = fileIo.writeSync(file.fd, "你好,世界"); +fileIo.closeSync(file); +console.info(`GarbledCnCharacters The length of str is: ${writeLen}`); +let stream = fileIo.createStreamSync(filePath, "r+"); +let buffer = new ArrayBuffer(4096); +stream.readSync(buffer); +// 设置编码格式为“utf-8” +let textDecoder = util.TextDecoder.create('utf-8', { ignoreBOM: true }); +// 解码输后获取对应文本 +let readString = textDecoder.decodeToString(new Uint8Array(buffer), { stream: false }); +console.info(`GarbledCnCharacters read content is:${readString}`); +// DocsCode 1 \ No newline at end of file diff --git a/CoreFileKit/entry/src/main/ets/pages/Index.ets b/CoreFileKit/entry/src/main/ets/pages/Index.ets new file mode 100644 index 0000000000000000000000000000000000000000..8e2d24ad42693fc877d51bb7820f0a9da68fa135 --- /dev/null +++ b/CoreFileKit/entry/src/main/ets/pages/Index.ets @@ -0,0 +1,23 @@ +@Entry +@Component +struct Index { + @State message: string = 'Hello World'; + + build() { + RelativeContainer() { + Text(this.message) + .id('HelloWorld') + .fontSize($r('app.float.page_text_font_size')) + .fontWeight(FontWeight.Bold) + .alignRules({ + center: { anchor: '__container__', align: VerticalAlign.Center }, + middle: { anchor: '__container__', align: HorizontalAlign.Center } + }) + .onClick(() => { + this.message = 'Welcome'; + }) + } + .height('100%') + .width('100%') + } +} \ No newline at end of file diff --git a/CoreFileKit/entry/src/main/ets/pages/StreamDataToFile.ets b/CoreFileKit/entry/src/main/ets/pages/StreamDataToFile.ets new file mode 100644 index 0000000000000000000000000000000000000000..1ffa41627cb483cbf4da10adace49da67b6224de --- /dev/null +++ b/CoreFileKit/entry/src/main/ets/pages/StreamDataToFile.ets @@ -0,0 +1,61 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何将数据持续写入文件内 +*/ + +// DocsCode 1 +import { fileIo, WriteOptions } from '@kit.CoreFileKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +@Component +export struct ContinuousWrite { + @State message: string = 'Hello World'; + + aboutToAppear(): void { + let context = this.getUIContext().getHostContext(); // 沙箱路径 + let filePath = context!.filesDir + '/test.txt'; + let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE); + let arrayBuffer = new ArrayBuffer(4096); + fileIo.read(file.fd, arrayBuffer).then((readLen: number) => { + console.info(readLen.toString()); + let str: string = 'hello, world'; + let options: WriteOptions = { offset: readLen }; + let writeLen = fileIo.writeSync(file.fd, str, options); + console.info('write data to file succeed and size is:' + writeLen); + }).catch((err: BusinessError) => { + console.error('read file data failed with error message: ' + err.message + ', error code: ' + err.code); + }).finally(() => { + fileIo.closeSync(file); + }); + } + + build() { + RelativeContainer() { + Text(this.message) + .id('WriteHelloWorld') + .fontSize(50) + .fontWeight(FontWeight.Bold) + .alignRules({ + center: { anchor: '__container__', align: VerticalAlign.Center }, + middle: { anchor: '__container__', align: HorizontalAlign.Center } + }) + } + .height('100%') + .width('100%') + } +} +// DocsCode 1 \ No newline at end of file diff --git a/CoreFileKit/entry/src/main/ets/pages/UpdateSandboxJson.ets b/CoreFileKit/entry/src/main/ets/pages/UpdateSandboxJson.ets new file mode 100644 index 0000000000000000000000000000000000000000..b4b4207ef7bbc72191954fda40764a52af3f8ece --- /dev/null +++ b/CoreFileKit/entry/src/main/ets/pages/UpdateSandboxJson.ets @@ -0,0 +1,49 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何修改沙箱路径下json文件的指定内容 +*/ + +// DocsCode 1 +import { fileIo } from '@kit.CoreFileKit'; + +// 工具类中:在EntryAbility中获取Context后保存至AppStorage,然后在工具类中使用AppStorage获取 +let context = AppStorage.get("context") as UIContext; +let filePath = context.getHostContext()!.filesDir + '/people.json'; + +class Student { + name: string = 'zhangsan'; + age: number = 10; +} + +let student = new Student(); +// 1 创建文件,并且写入内容 +let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); +fileIo.writeSync(file.fd, JSON.stringify(student)) +fileIo.close(file); +// 2 通过fileIo.readSync读取json文件内容。 +let data = fileIo.readTextSync(filePath); +let obj: Student = JSON.parse(data); +// 3 修改指定内容name为lisi +obj.name = 'lisi'; +// 4 重新写入json文件 +let fileModify = fileIo.openSync(filePath, fileIo.OpenMode.WRITE_ONLY | fileIo.OpenMode.TRUNC); +fileIo.writeSync(fileModify.fd, JSON.stringify(obj)); +fileIo.close(fileModify); +// 5 读取最新内容 +let content = fileIo.readTextSync(filePath); +console.info(`ModifySanFileContent content is :${content}`); +// DocsCode 1 \ No newline at end of file diff --git a/CoreFileKit/entry/src/main/module.json5 b/CoreFileKit/entry/src/main/module.json5 new file mode 100644 index 0000000000000000000000000000000000000000..a1cea8b6a4560cee7bda7a2db52f310c035ab6c8 --- /dev/null +++ b/CoreFileKit/entry/src/main/module.json5 @@ -0,0 +1,52 @@ +{ + "module": { + "name": "entry", + "type": "entry", + "description": "$string:module_desc", + "mainElement": "EntryAbility", + "deviceTypes": [ + "phone", + "tablet", + "2in1" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:main_pages", + "abilities": [ + { + "name": "EntryAbility", + "srcEntry": "./ets/entryability/EntryAbility.ets", + "description": "$string:EntryAbility_desc", + "icon": "$media:layered_image", + "label": "$string:EntryAbility_label", + "startWindowIcon": "$media:startIcon", + "startWindowBackground": "$color:start_window_background", + "exported": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ] + } + ], + "extensionAbilities": [ + { + "name": "EntryBackupAbility", + "srcEntry": "./ets/entrybackupability/EntryBackupAbility.ets", + "type": "backup", + "exported": false, + "metadata": [ + { + "name": "ohos.extension.backup", + "resource": "$profile:backup_config" + } + ], + } + ] + } +} \ No newline at end of file diff --git a/CoreFileKit/entry/src/main/resources/base/element/color.json b/CoreFileKit/entry/src/main/resources/base/element/color.json new file mode 100644 index 0000000000000000000000000000000000000000..3c712962da3c2751c2b9ddb53559afcbd2b54a02 --- /dev/null +++ b/CoreFileKit/entry/src/main/resources/base/element/color.json @@ -0,0 +1,8 @@ +{ + "color": [ + { + "name": "start_window_background", + "value": "#FFFFFF" + } + ] +} \ No newline at end of file diff --git a/CoreFileKit/entry/src/main/resources/base/element/float.json b/CoreFileKit/entry/src/main/resources/base/element/float.json new file mode 100644 index 0000000000000000000000000000000000000000..33ea22304f9b1485b5f22d811023701b5d4e35b6 --- /dev/null +++ b/CoreFileKit/entry/src/main/resources/base/element/float.json @@ -0,0 +1,8 @@ +{ + "float": [ + { + "name": "page_text_font_size", + "value": "50fp" + } + ] +} diff --git a/CoreFileKit/entry/src/main/resources/base/element/string.json b/CoreFileKit/entry/src/main/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..f94595515a99e0c828807e243494f57f09251930 --- /dev/null +++ b/CoreFileKit/entry/src/main/resources/base/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "label" + } + ] +} \ No newline at end of file diff --git a/CoreFileKit/entry/src/main/resources/base/media/background.png b/CoreFileKit/entry/src/main/resources/base/media/background.png new file mode 100644 index 0000000000000000000000000000000000000000..923f2b3f27e915d6871871deea0420eb45ce102f Binary files /dev/null and b/CoreFileKit/entry/src/main/resources/base/media/background.png differ diff --git a/CoreFileKit/entry/src/main/resources/base/media/foreground.png b/CoreFileKit/entry/src/main/resources/base/media/foreground.png new file mode 100644 index 0000000000000000000000000000000000000000..97014d3e10e5ff511409c378cd4255713aecd85f Binary files /dev/null and b/CoreFileKit/entry/src/main/resources/base/media/foreground.png differ diff --git a/CoreFileKit/entry/src/main/resources/base/media/layered_image.json b/CoreFileKit/entry/src/main/resources/base/media/layered_image.json new file mode 100644 index 0000000000000000000000000000000000000000..fb49920440fb4d246c82f9ada275e26123a2136a --- /dev/null +++ b/CoreFileKit/entry/src/main/resources/base/media/layered_image.json @@ -0,0 +1,7 @@ +{ + "layered-image": + { + "background" : "$media:background", + "foreground" : "$media:foreground" + } +} \ No newline at end of file diff --git a/CoreFileKit/entry/src/main/resources/base/media/startIcon.png b/CoreFileKit/entry/src/main/resources/base/media/startIcon.png new file mode 100644 index 0000000000000000000000000000000000000000..205ad8b5a8a42e8762fbe4899b8e5e31ce822b8b Binary files /dev/null and b/CoreFileKit/entry/src/main/resources/base/media/startIcon.png differ diff --git a/CoreFileKit/entry/src/main/resources/base/profile/backup_config.json b/CoreFileKit/entry/src/main/resources/base/profile/backup_config.json new file mode 100644 index 0000000000000000000000000000000000000000..78f40ae7c494d71e2482278f359ec790ca73471a --- /dev/null +++ b/CoreFileKit/entry/src/main/resources/base/profile/backup_config.json @@ -0,0 +1,3 @@ +{ + "allowToBackupRestore": true +} \ No newline at end of file diff --git a/CoreFileKit/entry/src/main/resources/base/profile/main_pages.json b/CoreFileKit/entry/src/main/resources/base/profile/main_pages.json new file mode 100644 index 0000000000000000000000000000000000000000..1898d94f58d6128ab712be2c68acc7c98e9ab9ce --- /dev/null +++ b/CoreFileKit/entry/src/main/resources/base/profile/main_pages.json @@ -0,0 +1,5 @@ +{ + "src": [ + "pages/Index" + ] +} diff --git a/CoreFileKit/entry/src/main/resources/dark/element/color.json b/CoreFileKit/entry/src/main/resources/dark/element/color.json new file mode 100644 index 0000000000000000000000000000000000000000..79b11c2747aec33e710fd3a7b2b3c94dd9965499 --- /dev/null +++ b/CoreFileKit/entry/src/main/resources/dark/element/color.json @@ -0,0 +1,8 @@ +{ + "color": [ + { + "name": "start_window_background", + "value": "#000000" + } + ] +} \ No newline at end of file diff --git a/CoreFileKit/entry/src/mock/mock-config.json5 b/CoreFileKit/entry/src/mock/mock-config.json5 new file mode 100644 index 0000000000000000000000000000000000000000..7a73a41bfdf76d6f793007240d80983a52f15f97 --- /dev/null +++ b/CoreFileKit/entry/src/mock/mock-config.json5 @@ -0,0 +1,2 @@ +{ +} \ No newline at end of file diff --git a/CoreFileKit/entry/src/ohosTest/ets/test/Ability.test.ets b/CoreFileKit/entry/src/ohosTest/ets/test/Ability.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..85c78f67579d6e31b5f5aeea463e216b9b141048 --- /dev/null +++ b/CoreFileKit/entry/src/ohosTest/ets/test/Ability.test.ets @@ -0,0 +1,35 @@ +import { hilog } from '@kit.PerformanceAnalysisKit'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'; + +export default function abilityTest() { + describe('ActsAbilityTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }) + beforeEach(() => { + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }) + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }) + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }) + it('assertContain', 0, () => { + // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. + hilog.info(0x0000, 'testTag', '%{public}s', 'it begin'); + let a = 'abc'; + let b = 'b'; + // Defines a variety of assertion methods, which are used to declare expected boolean conditions. + expect(a).assertContain(b); + expect(a).assertEqual(a); + }) + }) +} \ No newline at end of file diff --git a/CoreFileKit/entry/src/ohosTest/ets/test/List.test.ets b/CoreFileKit/entry/src/ohosTest/ets/test/List.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..794c7dc4ed66bd98fa3865e07922906e2fcef545 --- /dev/null +++ b/CoreFileKit/entry/src/ohosTest/ets/test/List.test.ets @@ -0,0 +1,5 @@ +import abilityTest from './Ability.test'; + +export default function testsuite() { + abilityTest(); +} \ No newline at end of file diff --git a/CoreFileKit/entry/src/ohosTest/module.json5 b/CoreFileKit/entry/src/ohosTest/module.json5 new file mode 100644 index 0000000000000000000000000000000000000000..55725a929993a8a18b3808d41ef037759440488b --- /dev/null +++ b/CoreFileKit/entry/src/ohosTest/module.json5 @@ -0,0 +1,13 @@ +{ + "module": { + "name": "entry_test", + "type": "feature", + "deviceTypes": [ + "phone", + "tablet", + "2in1" + ], + "deliveryWithInstall": true, + "installationFree": false + } +} diff --git a/CoreFileKit/entry/src/test/List.test.ets b/CoreFileKit/entry/src/test/List.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..bb5b5c3731e283dd507c847560ee59bde477bbc7 --- /dev/null +++ b/CoreFileKit/entry/src/test/List.test.ets @@ -0,0 +1,5 @@ +import localUnitTest from './LocalUnit.test'; + +export default function testsuite() { + localUnitTest(); +} \ No newline at end of file diff --git a/CoreFileKit/entry/src/test/LocalUnit.test.ets b/CoreFileKit/entry/src/test/LocalUnit.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..165fc1615ee8618b4cb6a622f144a9a707eee99f --- /dev/null +++ b/CoreFileKit/entry/src/test/LocalUnit.test.ets @@ -0,0 +1,33 @@ +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'; + +export default function localUnitTest() { + describe('localUnitTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }); + beforeEach(() => { + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }); + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }); + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }); + it('assertContain', 0, () => { + // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. + let a = 'abc'; + let b = 'b'; + // Defines a variety of assertion methods, which are used to declare expected boolean conditions. + expect(a).assertContain(b); + expect(a).assertEqual(a); + }); + }); +} \ No newline at end of file diff --git a/CoreFileKit/hvigor/hvigor-config.json5 b/CoreFileKit/hvigor/hvigor-config.json5 new file mode 100644 index 0000000000000000000000000000000000000000..a63d34ae5ce5833b3874807e2b8d472687c6c5bf --- /dev/null +++ b/CoreFileKit/hvigor/hvigor-config.json5 @@ -0,0 +1,22 @@ +{ + "modelVersion": "5.0.4", + "dependencies": { + }, + "execution": { + // "analyze": "normal", /* Define the build analyze mode. Value: [ "normal" | "advanced" | false ]. Default: "normal" */ + // "daemon": true, /* Enable daemon compilation. Value: [ true | false ]. Default: true */ + // "incremental": true, /* Enable incremental compilation. Value: [ true | false ]. Default: true */ + // "parallel": true, /* Enable parallel compilation. Value: [ true | false ]. Default: true */ + // "typeCheck": false, /* Enable typeCheck. Value: [ true | false ]. Default: false */ + }, + "logging": { + // "level": "info" /* Define the log level. Value: [ "debug" | "info" | "warn" | "error" ]. Default: "info" */ + }, + "debugging": { + // "stacktrace": false /* Disable stacktrace compilation. Value: [ true | false ]. Default: false */ + }, + "nodeOptions": { + // "maxOldSpaceSize": 8192 /* Enable nodeOptions maxOldSpaceSize compilation. Unit M. Used for the daemon process. Default: 8192*/ + // "exposeGC": true /* Enable to trigger garbage collection explicitly. Default: true*/ + } +} diff --git a/CoreFileKit/hvigorfile.ts b/CoreFileKit/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..f3cb9f1a87a81687554a76283af8df27d8bda775 --- /dev/null +++ b/CoreFileKit/hvigorfile.ts @@ -0,0 +1,6 @@ +import { appTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins:[] /* Custom plugin to extend the functionality of Hvigor. */ +} diff --git a/CoreFileKit/oh-package-lock.json5 b/CoreFileKit/oh-package-lock.json5 new file mode 100644 index 0000000000000000000000000000000000000000..c6f99f5c73b06c5fdef7ec6f491b74b7befebe2e --- /dev/null +++ b/CoreFileKit/oh-package-lock.json5 @@ -0,0 +1,27 @@ +{ + "meta": { + "stableOrder": true + }, + "lockfileVersion": 3, + "ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.", + "specifiers": { + "@ohos/hamock@1.0.0": "@ohos/hamock@1.0.0", + "@ohos/hypium@1.0.21": "@ohos/hypium@1.0.21" + }, + "packages": { + "@ohos/hamock@1.0.0": { + "name": "@ohos/hamock", + "version": "1.0.0", + "integrity": "sha512-K6lDPYc6VkKe6ZBNQa9aoG+ZZMiwqfcR/7yAVFSUGIuOAhPvCJAo9+t1fZnpe0dBRBPxj2bxPPbKh69VuyAtDg==", + "resolved": "https://repo.harmonyos.com/ohpm/@ohos/hamock/-/hamock-1.0.0.har", + "registryType": "ohpm" + }, + "@ohos/hypium@1.0.21": { + "name": "@ohos/hypium", + "version": "1.0.21", + "integrity": "sha512-iyKGMXxE+9PpCkqEwu0VykN/7hNpb+QOeIuHwkmZnxOpI+dFZt6yhPB7k89EgV1MiSK/ieV/hMjr5Z2mWwRfMQ==", + "resolved": "https://repo.harmonyos.com/ohpm/@ohos/hypium/-/hypium-1.0.21.har", + "registryType": "ohpm" + } + } +} \ No newline at end of file diff --git a/CoreFileKit/oh-package.json5 b/CoreFileKit/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..75e4e229db0f608fc3d9471c8819d0e52fb403c5 --- /dev/null +++ b/CoreFileKit/oh-package.json5 @@ -0,0 +1,10 @@ +{ + "modelVersion": "5.0.4", + "description": "Please describe the basic information.", + "dependencies": { + }, + "devDependencies": { + "@ohos/hypium": "1.0.21", + "@ohos/hamock": "1.0.0" + } +}