1/* 2 * Copyright (c) 2023 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 */ 15 16import common from '@ohos.app.ability.common'; 17import fs from '@ohos.file.fs'; 18import { logger } from '../utils/Logger'; 19 20const TAG: string = 'FileUtil'; 21const ALBUMS: string[] = ['Pictures', 'Videos', 'Others']; 22 23class FileUtil { 24 constructor() { 25 } 26 27 async initDownloadDir(): Promise<void> { 28 let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; 29 logger.info(TAG, `initDownloadDir cacheDir=${context.cacheDir}`); 30 try { 31 fs.mkdirSync(`${context.cacheDir}/${ALBUMS[0]}`); 32 fs.mkdirSync(`${context.cacheDir}/${ALBUMS[1]}`); 33 fs.mkdirSync(`${context.cacheDir}/${ALBUMS[2]}`); 34 } catch (err) { 35 logger.info(TAG, `initDownloadDir err =${JSON.stringify(err)}`); 36 } 37 } 38 39 async listFolders(): Promise<Array<string>> { 40 await this.initDownloadDir(); 41 return ALBUMS; 42 } 43 44 async clearFolder(folderName: string): Promise<void> { 45 let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; 46 try { 47 let files: string[] = fs.listFileSync(`${context.cacheDir}/${folderName}`); 48 logger.info(TAG, `listFiles listFileSync =${JSON.stringify(files)}`); 49 for (let i = 0; i < files.length; i++) { 50 fs.unlinkSync(`${context.cacheDir}/${folderName}/${files[i]}`); 51 } 52 } catch (err) { 53 logger.info(TAG, `listFiles err =${JSON.stringify(err)}`); 54 } 55 } 56 57 async listFiles(folderName: string): Promise<Array<string>> { 58 let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; 59 let files: string[] = []; 60 try { 61 files = fs.listFileSync(`${context.cacheDir}/${folderName}`); 62 logger.info(TAG, `listFiles listFileSync =${JSON.stringify(files)}`); 63 } catch (err) { 64 logger.info(TAG, `listFiles err =${JSON.stringify(err)}`); 65 } 66 return files; 67 } 68} 69 70export const fileUtils = new FileUtil();