1/* 2 * Copyright (c) 2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15import dataStorage from '@ohos.data.storage'; 16import featureAbility from '@ohos.ability.featureAbility'; 17import { Logger } from '../components/Logger' 18 19@Entry 20@Component 21struct SwitchControl { 22 build() { 23 } 24} 25 26export function readFile(key) { 27 let context = featureAbility.getContext() 28 return context.getFilesDir().then((path) => { 29 let promise 30 try { 31 promise = dataStorage.getStorage(`${path}/mystore`) 32 } catch (err) { 33 Logger.error(`getStorage failed, code is ${err.code}, message is ${err.message}`) 34 } 35 return promise.then((storage) => { 36 let readText = storage.get(key, 'default') 37 return readText.then((value) => { 38 return new Promise((resolve) => { 39 return resolve(value) 40 }) 41 }) 42 }) 43 }) 44} 45 46export function writeFile({ key="", val="" }) { 47 // 读取文件 48 let context = featureAbility.getContext() 49 context.getFilesDir().then((path) => { 50 // 获取实例 51 let storage 52 try { 53 storage = dataStorage.getStorageSync(`${path}/mystore`) 54 } catch (err) { 55 Logger.error(`getStorageSync failed, code is ${err.code}, message is ${err.message}`) 56 } 57 // 将数据写入 58 storage.putSync(key, val) 59 // 持久化储存 60 storage.flushSync() 61 }) 62}