1/* 2 * Copyright (c) 2024-2025 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 fs from '@ohos.file.fs'; 17import CommonUtil from '../CommonUtil'; 18import { HiLog } from '../HiLog'; 19 20const TAG = 'FileUtil'; 21 22export default class FileUtil { 23 public static closeSync(file: fs.File | number | undefined): void { 24 if (!file) { 25 HiLog.error(TAG, 'closeSync param is invalid.'); 26 return; 27 } 28 try { 29 fs.closeSync(file); 30 HiLog.info(TAG, 'closeSync success.'); 31 } catch (err) { 32 HiLog.wrapError(TAG, err, 'closeSync failed'); 33 } 34 } 35 36 public static unlinkSync(uri: string): void { 37 if (CommonUtil.isEmptyStr(uri)) { 38 HiLog.error(TAG, 'unlinkSync param is invalid.'); 39 return; 40 } 41 try { 42 const isExist = fs.accessSync(uri); 43 if (isExist) { 44 fs.unlinkSync(uri); 45 } 46 HiLog.info(TAG, 'unlinkSync success.'); 47 } catch (err) { 48 HiLog.wrapError(TAG, err, 'unlinkSync failed'); 49 } 50 } 51 52 public static rmdirSync(uri: string): void { 53 if (CommonUtil.isEmptyStr(uri)) { 54 HiLog.error(TAG, 'removeDir: param is invalid.'); 55 return; 56 } 57 try { 58 let res = fs.accessSync(uri); 59 if (res) { 60 fs.rmdirSync(uri); 61 } 62 } catch (err) { 63 HiLog.wrapError(TAG, err, 'rmdirSync failed'); 64 } 65 } 66 67 public static async unlink(uri: string): Promise<void> { 68 if (CommonUtil.isEmptyStr(uri)) { 69 HiLog.error(TAG, 'unlink: param is invalid.'); 70 return; 71 } 72 try { 73 await fs.unlink(uri); 74 } catch (err) { 75 HiLog.wrapError(TAG, err, 'unlink failed'); 76 } 77 } 78}