电子说
本示例主要展示了文件管理相关的功能,使用[@ohos.multimedia.medialibrary]、[@ohos.filemanagement.userFileManager] 、[@ohos.fileio] 、[@ohos.file.fs]、[@ohos.app.ability.contextConstant]
等接口,实现了增添文件、删除文件、查找指定类型文件文件、复制并移动文件、切换加密分区和预览图片、监听文件的功能;
使用说明
/*
* Copyright (c) 2022-2023 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.
*/
import image from '@ohos.multimedia.image'
import mediaLibrary from '@ohos.multimedia.mediaLibrary'
import Logger from '../../utils/Logger'
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
import type { Permissions } from '@ohos.abilityAccessCtrl';
/**
* 主要封装了mediaLibrary库相关的接口
*/
class MediaLibraryManager {
requestPermission(context): void {
let permissions: Array< Permissions > = [
'ohos.permission.READ_MEDIA',
'ohos.permission.WRITE_MEDIA'
]
let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
atManager.requestPermissionsFromUser(context, permissions, (code, result) = > {
Logger.debug('permissionRequest ' + JSON.stringify(code) + ' Result: ' + JSON.stringify(result))
})
}
async getPixelMapByFileAsset(fileAsset: mediaLibrary.FileAsset): Promise< image.PixelMap > {
if (fileAsset == undefined) {
Logger.error('fileAsset undefined')
// 异常情况下统一返回undefined,不建议使用null
return undefined
}
Logger.debug('begin getPixelMapByFileAsset:' + fileAsset.displayName)
let fd: number = undefined
let pixelMap = undefined
try {
fd = await fileAsset.open('rw')
Logger.debug('getPixelMapByFileAsset fd: ' + fd)
let imageSource = image.createImageSource(fd)
Logger.debug('imageSource: ' + JSON.stringify(imageSource))
let decodingOptions = {
sampleSize: 1,
editable: true,
desiredSize: { width: 3000, height: 4000 },
rotate: 0,
desiredPixelFormat: 3,
desiredRegion: { size: { height: 6000, width: 8000 }, x: 0, y: 0 },
index: 0
}
pixelMap = await imageSource.createPixelMap(decodingOptions)
Logger.debug('pixel size: ' + pixelMap.getPixelBytesNumber())
fileAsset.close(fd)
} catch (err) {
Logger.debug('err: ' + JSON.stringify(err))
}
return pixelMap
}
getMediaLibrary(context): mediaLibrary.MediaLibrary {
return mediaLibrary.getMediaLibrary(context)
}
async getFileAssets(context, fileType: mediaLibrary.MediaType): Promise< mediaLibrary.FetchFileResult > {
Logger.debug('begin getFileAssets, fileType:' + fileType)
let fileKeyObj = mediaLibrary.FileKey
let imagesFetchOption = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()],
}
let fetchFileResult: mediaLibrary.FetchFileResult = undefined
try {
fetchFileResult = await this.getMediaLibrary(context).getFileAssets(imagesFetchOption)
Logger.debug('fetchFileResult count:' + fetchFileResult.getCount())
} catch (error) {
Logger.error('fetchFileResult Error: ' + JSON.stringify(error))
}
return fetchFileResult
}
async getFileAssetsByName(context, name: string): Promise< mediaLibrary.FileAsset > {
Logger.debug('begin getFileAssetsByName: ' + name)
let fileKeyObj = mediaLibrary.FileKey
let imagesFetchOption = {
selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: [name.toString()],
}
let fetchFileResult: mediaLibrary.FetchFileResult = undefined
let file: mediaLibrary.FileAsset = undefined
try {
fetchFileResult = await this.getMediaLibrary(context).getFileAssets(imagesFetchOption)
Logger.debug('fetchFileResult count:' + fetchFileResult.getCount())
file = await fetchFileResult.getFirstObject()
} catch (error) {
Logger.error('fetchFileResult Error: ' + JSON.stringify(error))
}
return file
}
async getThumbnail(fileAsset: mediaLibrary.FileAsset): Promise< image.PixelMap > {
let thumbnail = undefined
try {
thumbnail = await fileAsset.getThumbnail()
Logger.debug('PixelMap size: ' + thumbnail.getPixelBytesNumber())
} catch (error) {
Logger.error('getThumbnail Error: ' + JSON.stringify(error))
}
return thumbnail
}
async createFileAsset(context, mediaType: mediaLibrary.MediaType,
dir: mediaLibrary.DirectoryType, fileName: string): Promise< mediaLibrary.FileAsset > {
Logger.debug('createFileAsset: ' + fileName)
let media = this.getMediaLibrary(context)
let path = await media.getPublicDirectory(dir)
return await media.createAsset(mediaType, fileName, path)
}
async deleteFileAsset(fileAsset: mediaLibrary.FileAsset): Promise< void > {
Logger.debug('deleteFileAsset:' + fileAsset.displayName);
await fileAsset.trash(true);
}
}
export default new MediaLibraryManager()
/*
* Copyright (c) 2023 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.
*/
import storageStatistics from '@ohos.file.storageStatistics';
import fileio from '@ohos.fileio';
import prompt from '@ohos.promptAction';
import { BusinessError } from '@ohos.base';
import Logger from '../../utils/Logger';
import { FileType, SubDirectoryType } from '../../mock/local/FileData';
// 大小和单位
const GB_MAGNITUDE: number = 1024 * 1024 * 1024;
const MB_MAGNITUDE: number = 1024 * 1024;
const KB_MAGNITUDE: number = 1024;
const GB_SYMBOL: string = 'GB';
const MB_SYMBOL: string = 'MB';
const KB_SYMBOL: string = 'KB';
const BYTE_SYMBOL: string = 'B';
const TAG: string = 'FileIoManager';
class FileSystem {
// 获取文件大小
getFileSize(filePath: string): string {
try {
let fileSize = fileio.statSync(filePath).size;
if (fileSize / GB_MAGNITUDE > 1) {
return `${(fileSize / GB_MAGNITUDE).toFixed(2)}${GB_SYMBOL}`;
} else if (fileSize / MB_MAGNITUDE > 1) {
return `${(fileSize / MB_MAGNITUDE).toFixed(2)}${MB_SYMBOL}`;
} else if (fileSize / KB_MAGNITUDE > 1) {
return `${(fileSize / KB_MAGNITUDE).toFixed(2)}${KB_SYMBOL}`;
} else {
return `${fileSize}${BYTE_SYMBOL}`;
}
} catch (err) {
Logger.error(TAG, `getFileSize failed, code is ${err.code}, message is ${err.message}`);
throw new Error(`getFileSize failed, code is ${err.code}, message is ${err.message}`);
}
}
/*
// 总空间---默认GB
async getTotalSize(): Promise< string > {
let totalSize: number;
try {
totalSize = await storageStatistics.getTotalSize();
} catch (err) {
let error: BusinessError = err as BusinessError;
Logger.error(TAG, `getTotalSize failed, code is ${error.code}, message is ${error.message}`);
throw new Error(`getTotalSize failed, code is ${error.code}, message is ${error.message}`);
}
return `${(totalSize / GB_MAGNITUDE).toFixed(2)}${GB_SYMBOL}`;
}
// 剩余空间
async getFreeSize(): Promise< string > {
let freeSize: number;
try {
freeSize = await storageStatistics.getFreeSize();
} catch (err) {
let error: BusinessError = err as BusinessError;
Logger.error(TAG, `getFreeSize failed, code is ${error.code}, message is ${error.message}`);
throw new Error(`getFreeSize failed, code is ${error.code}, message is ${error.message}`);
}
if (freeSize / GB_MAGNITUDE > 1) {
return `${(freeSize / GB_MAGNITUDE).toFixed(2)}${GB_SYMBOL}`;
} else if (freeSize / MB_MAGNITUDE > 1) {
return `${(freeSize / MB_MAGNITUDE).toFixed(2)}${MB_SYMBOL}`;
} else if (freeSize / KB_MAGNITUDE > 1) {
return `${(freeSize / KB_MAGNITUDE).toFixed(2)}${KB_SYMBOL}`;
} else {
return `${freeSize}${BYTE_SYMBOL}`;
}
}
*/
// 根据沙箱路径打开目录
getSubdirectory(filePath: string): Array< SubDirectoryType > {
// 获取目录
let dir: fileio.Dir;
try {
dir = fileio.opendirSync(filePath);
} catch (err) {
let error: BusinessError = err as BusinessError;
Logger.error(TAG, `Open dir of path ${filePath} failed. error code is ${error.code}, message is ${error.message}`);
throw new Error(`Open dir of path ${filePath} failed, code is ${error.code}, message is ${error.message}`);
}
// 读取的结果
let dirent: fileio.Dirent;
// 结果数组
class SubDirectory {
name: string = '';
type: number = 0;
time: Date;
childrenNum: number = 0;
fileSize: string = '';
constructor(time: Date) {
this.time = time;
}
}
let subdirectory: Array< SubDirectory > = []
do {
dirent = dir.readSync();
if (dirent) {
let subdirectoryNum: number = 0;
let fileSize: string = '';
let time: Date = new Date();
// 如果是文件夹,就读取文件夹中文件的数量
if (dirent.isDirectory()) {
subdirectoryNum = this.getSubdirectoryNum(filePath + `${dirent.name}`);
time = this.getFileTime(filePath + `${dirent.name}`);
} else {
// 如果不是文件夹,就读取文件大小和时间
fileSize = this.getFileSize(filePath + `${dirent.name}`);
time = this.getFileTime(filePath + `${dirent.name}`);
}
let item = new SubDirectory(time);
item.name = dirent.name;
item.type = dirent.isDirectory() ? 1 : 2;
item.childrenNum = subdirectoryNum;
item.fileSize = fileSize;
subdirectory.push(item);
}
} while (dirent);
return subdirectory;
}
// 获取目录中的子目录个数
getSubdirectoryNum(filePath: string): number {
let dir: fileio.Dir;
try {
dir = fileio.opendirSync(filePath);
} catch (err) {
let error: BusinessError = err as BusinessError;
Logger.error(TAG, `Open dir of path ${filePath} failed. error code is ${error.code}, message is ${error.message}`);
throw new Error(`Open dir of path ${filePath} failed, code is ${error.code}, message is ${error.message}`);
}
// 读取的结果
let dirent: fileio.Dirent;
// 记录子目录的个数
let subdirectoryNum = 0;
do {
dirent = dir.readSync();
if (dirent) {
subdirectoryNum++;
}
} while (dirent);
return subdirectoryNum;
}
// 获取文件修改时间
getFileTime(filePath: string): Date {
try {
let fileTime = fileio.statSync(filePath).mtime;
return new Date(fileTime * 1000);
} catch (err) {
Logger.error(TAG, `getFileTime failed, code is ${err.code}, message is ${err.message}`);
throw new Error(`getFileTime failed, code is ${err.code}, message is ${err.message}`);
}
}
// 创建目录
createDirectory(filePath: string): void {
try {
fileio.mkdirSync(filePath);
} catch (err) {
Logger.error(TAG, `create directory failed, code is ${err.code}, message is ${err.message}`);
}
}
// 创建文件
createFile(filePath: string): void {
try {
fileio.openSync(filePath, 0o100, 0o666);
} catch (err) {
Logger.error(TAG, `create file failed, code is ${err.code}, message is ${err.message}`);
}
}
// 删除目录和文件---选中项
deleteSelected(dataArray: Map< string, number >): void {
try {
dataArray.forEach((value, data) = > {
if (value === 1) {
fileio.rmdirSync(data);
} else {
fileio.unlinkSync(data);
}})
prompt.showToast({ message: $r('app.string.label_delete_success') });
} catch (err) {
Logger.error(TAG, `delete failed, code is ${err.code}, message is ${err.message}`);
}
}
// 复制文件
copyFile(filePath: string, newFilePath: string): void {
try {
// 遍历数据直接copy所有项目
fileio.copyFileSync(filePath, newFilePath);
} catch (err) {
Logger.error(TAG, `copy file failed, code is ${err.code}, message is ${err.message}`);
}
}
// 重命名文件
renameFile(filePath: string, newFilePath: string): void {
try {
fileio.renameSync(filePath, newFilePath);
} catch (err) {
Logger.error(TAG, `rename file failed, code is ${err.code}, message is ${err.message}`);
}
}
// 开始移动文件
startMoveFile(needMoveFiles: Array< FileType >, newFilePath: string): void {
// 遍历数据
needMoveFiles.forEach((file: FileType): void = > {
// 如果是目录
if (file.type === 1) {
// 先创建这个目录
this.createDirectory(`${newFilePath}/${file.fileName}`);
// 获取当前文件夹下的所有文件目录
let subdirectory = this.getSubdirectory(`${file.filePath}/`);
// 处理为我们想要的格式
let needMoveFiles: Array< FileType > = [];
// 遍历子目录数据
subdirectory.forEach((subdirectoryData: SubDirectoryType) = > {
let data: FileType = {
filePath: `${file.filePath}/${subdirectoryData.name}`,
fileName: subdirectoryData.name,
type: subdirectoryData.type
};
// 逐一添加进去
needMoveFiles.push(data);
})
// 使用我们的数据递归
this.startMoveFile(needMoveFiles, `${newFilePath}/${file.fileName}`);
} else {
this.copyFile(file.filePath, `${newFilePath}/${file.fileName}`);
}
})
}
}
export default new FileSystem();
/*
* Copyright (c) 2022 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.
*/
import mediaLibrary from '@ohos.multimedia.mediaLibrary'
import image from '@ohos.multimedia.image'
import MediaLibraryManager from './medialibrary/MediaLibraryManager'
import LocalMockData from '../mock/local/LocalMockData'
/**
* 文件管理接口,统一封装了各模块对外提供的功能接口
*/
class FileManager {
/**
* 申请文件管理权限
* @param context 上下文对象
*/
requestPermission(context): void {
MediaLibraryManager.requestPermission(context)
}
/**
* 通过传入文件对象FileAsset,获取到文件中的图片PixelMap对象
* @param fileAsset 文件对象
* @return Promise< image.PixelMap > 返回PixelMap对象
*/
async getPixelMapByFileAsset(fileAsset: mediaLibrary.FileAsset): Promise< image.PixelMap > {
return await MediaLibraryManager.getPixelMapByFileAsset(fileAsset)
}
/**
* 通过传入文件类型,获取到不同的文件列表信息
* @param context 上下文对象
* @param fileType 文件类型
* @return Promise< mediaLibrary.FetchFileResult > 返回文件列表信息
*/
async getFileAssets(context, fileType: mediaLibrary.MediaType): Promise< mediaLibrary.FetchFileResult > {
return await MediaLibraryManager.getFileAssets(context, fileType)
}
/**
* 通过文件名称获取文件对象
* @param context 上下文对象
* @param name 文件名称
* @return Promise< mediaLibrary.FileAsset > 返回文件对象信息
*/
async getFileAssetsByName(context, name: string): Promise< mediaLibrary.FileAsset > {
return await MediaLibraryManager.getFileAssetsByName(context, name)
}
/**
* 获取文件缩略图
* @param fileAsset 文件对象
* @return Promise< image.PixelMap > 返回缩略图信息
*/
async getThumbnail(fileAsset: mediaLibrary.FileAsset): Promise< image.PixelMap > {
return await MediaLibraryManager.getThumbnail(fileAsset)
}
/**
* 创建文件
* @param context 上下文对象
* @param mediaType 文件类型
* @param dir 文件路径
* @param fileName 文件名称
* @return Promise< mediaLibrary.FileAsset > 返回匹配的文件信息
*/
async createFileAsset(context, mediaType: mediaLibrary.MediaType,
dir: mediaLibrary.DirectoryType, fileName: string): Promise< mediaLibrary.FileAsset > {
return await MediaLibraryManager.createFileAsset(context, mediaType, dir, fileName)
}
/**
* 删除文件
* @param fileAsset 文件对象
*/
async deleteFileAsset(fileAsset: mediaLibrary.FileAsset): Promise< void > {
await MediaLibraryManager.deleteFileAsset(fileAsset);
}
/**
* 创建模拟文件
* @param context 上下文对象
* @param mediaType 文件类型
* @return Promise< mediaLibrary.FileAsset > 返回文件对象
*/
async createTxtFileAsset(context): Promise< mediaLibrary.FileAsset > {
return await LocalMockData.createFileAsset(context)
}
/**
* 该文件是否支持预览
* @param fileName 文件名
* @return boolean ture表示支持,false表示不支持
*/
isSupportPreview(fileName: string): boolean {
return LocalMockData.isSupportPreview(fileName)
}
}
export default new FileManager()
中调用MyWatcher.modifyFileToWatcher()。
gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md
]请前往参考。审核编辑 黄宇
全部0条评论
快来发表一下你的评论吧 !