1/* 2 * Copyright (c) 2024 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 24 public static closeFileSync(file: fs.File | undefined): boolean { 25 if (!file) { 26 HiLog.error(TAG, 'param is invalid.'); 27 return false; 28 } 29 return FileUtil.closeSync(file); 30 } 31 32 public static closeFdSync(file: number): boolean { 33 return FileUtil.closeSync(file); 34 } 35 36 public static closeSync(file: fs.File | undefined | number): boolean { 37 try { 38 fs.closeSync(file); 39 HiLog.info(TAG, 'closeSync success.'); 40 } catch (e) { 41 HiLog.error(TAG, `closeSync failed: ${JSON.stringify(e)}`); 42 return false; 43 } 44 return true; 45 } 46 47 public static unlinkSync(uri: string): boolean { 48 if (CommonUtil.isEmptyStr(uri)) { 49 HiLog.error(TAG, 'param is invalid.'); 50 return false; 51 } 52 try { 53 const isExist = fs.accessSync(uri); 54 if (isExist) { 55 fs.unlinkSync(uri); 56 } 57 HiLog.info(TAG, 'unlinkSync success.'); 58 } catch (e) { 59 HiLog.error(TAG, `unlinkSync failed: ${JSON.stringify(e)}`); 60 return false; 61 } 62 return true; 63 } 64 65}