当前位置: 首页 > news >正文

uniapp中对于文件和文件夹的处理,内存的查询

目录

移动文件到指定文件夹

新增本地文件夹

设定本地文件过期时间,清除超时文件,释放内存

操作本地文件之----删除

uniapp获取设备剩余存储空间的方法

读取本地文件夹下的文件


移动文件到指定文件夹

	function moveTempFile(tempFilePath, targetFolderPath, targetFileName) {
		plus.io.resolveLocalFileSystemURL(tempFilePath, function(entry) {
			// 获取目标目录的Entry对象
			plus.io.resolveLocalFileSystemURL(targetFolderPath, function(dirEntry) {
				// 执行复制操作
				entry.copyTo(dirEntry, targetFileName, function(newEntry) {
					//删除临时文件
					plus.io.resolveLocalFileSystemURL(tempFilePath, (entry) => {
						entry.remove(() => {
							console.log('临时文件转移成功');
						}, function(error) {
							console.error('临时文件转移失败:' + error.code);
						});
					});
					if (targetFileName.endsWith("mp4")) {
						console.log('判断临时文件为视频文件');
						getVideoNum()
					}
				}, function(e) {
					console.error('文件复制失败: ' + JSON.stringify(e));
				});
			}, function(e) {
				console.error('无法访问目标目录: ' + JSON.stringify(e));
			});
		}, function(e) {
			console.error('无法访问源文件: ' + JSON.stringify(e));
		});
 
	}
}

新增本地文件夹

//创建一个新目录
function CreateNewDir(url, dirName) {
	//url值可支持相对路径URL、本地路径URL
	return new Promise((resolver, reject) => {
		plus.io.resolveLocalFileSystemURL(url, function(entry) {
			entry.getDirectory(dirName, {
				create: true,
				exclusive: false
			}, function(dir) {
				resolver(true)
			}, function(error) {
				reject(error.message)
				uni.showToast({
					title: dirName + '目录创建失败:' + error.message,
					duration: 2000,
					icon: 'none'
				});
			});
		}, function(e) {
			reject(error.message)
			uni.showToast({
				title: '获取目录失败:' + e.message,
				duration: 2000,
				icon: 'none'
			});
		});
	})
}

设定本地文件过期时间,清除超时文件,释放内存

dataNum为文件的保质期

	//获取当前n天之前的日期
			getDelTime(dataNum){
				let today = new Date();
				let nDaysAgo = new Date(today.setDate(today.getDate() - dataNum));
				let year = nDaysAgo.getFullYear();
				let month = nDaysAgo.getMonth() + 1; // 月份是从0开始的,所以需要加1
				let day = nDaysAgo.getDate();
				// 将年月日转换为数字格式的字符串,不带任何分隔符-------n天前的年月日
				let numericDate = year.toString() + 
								  (month < 10 ? '0' + month : month).toString() + 
								  (day < 10 ? '0' + day : day).toString();	
				this.delExpiredFile(Number(numericDate))
			},
 
			//循环遍历视频图片文件夹,遍历出n天前的文件list,并执行删除操作
			async delExpiredFile(maxTime){
				// console.log('maxTime',maxTime);
				//获取所有图片文件
				await this.getImgList(maxTime)
				//获取所有视频文件
				await this.getVideoList(maxTime)
 
			},
			
			getImgList(maxTime){
				// console.log('开始获取图片',maxTime);
				this.imgNameList=[]
				plus.io.resolveLocalFileSystemURL(
					"/storage/emulated/0/_A/img", //指定的目录
					(entry) => {
						let directoryReader = entry.createReader(); //获取读取目录对象
						directoryReader.readEntries(
							(entry) => { //历遍子目录
							entry.forEach((entryA)=> {
								if (entryA.isFile) {
									// 获取文件名
									let fileName = entryA.name;
									this.imgNameList.push(fileName)
								}
							});
							this.imgNameList.forEach((item)=> {
								let extractedString = item.substring(4, 12);
								let  result =Number(extractedString)
								if(result < maxTime){
									console.log("将要删除的图片名",item);
									this.delFile(item,"picture")
								}
							});
							},
							(err) => {
								console.log("访问目录失败");
							});
					},
					(err) => {
						console.log("访问指定目录失败:" + err.message);
				});
			},
			
			getVideoList(maxTime){
				this.videoNameList=[]
				plus.io.resolveLocalFileSystemURL(
					"/storage/emulated/0/_A/video", //指定的目录
					(entry) => {
						let directoryReader = entry.createReader(); //获取读取目录对象
						directoryReader.readEntries(
							(entry) => { //历遍子目录即可
							entry.forEach((entryB)=> {
									if (entryB.isFile) {
										// 获取文件名
										let fileName = entryB.name;
										this.videoNameList.push(fileName)
									}
								});
							this.videoNameList.forEach((item)=> {
								let extractedString = item.substring(6, 14);
								let  result =Number(extractedString)
								if(result < maxTime){
									this.delFile(item,"video")
								}
							});
							},
							(err) => {
								console.log("访问目录失败");
								
							});
					},
					(err) => {
						console.log("访问指定目录失败:" + err.message);
				});
			},
				
			//删除文件
			delFile(fileName,fileType){
				console.log('将要删除的文件名fileName',fileName);
				return new Promise((resolve, reject) => {
					let filePath=null
					if(fileType=="video"){
						filePath=`/storage/emulated/0/_A/video/${fileName}`
					}else if(fileType=="picture"){
						filePath=`/storage/emulated/0/_A/img/${fileName}`
					}
					//删除视频文件					
					plus.io.resolveLocalFileSystemURL(filePath, (entry)=> {   
						 // 删除文件
						entry.remove(()=> {
							console.log('文件删除成功');
						}, function(error) {
							console.error('文件删除失败:' + error.code);
						});
					});
				})
			},

操作本地文件之----删除

delFile(fileName,fileType){
		return new Promise((resolve, reject) => {
			let filePath=null
			if(fileType=="video"){
				filePath=`/storage/emulated/0/_A/video/${fileName}`
			}else if(fileType=="picture"){
				filePath=`/storage/emulated/0/_A/img/${fileName}`
			}				
			//删除视频文件					
			plus.io.resolveLocalFileSystemURL(filePath, (entry)=> {   
				 // 删除文件
				entry.remove(()=> {
					console.log('文件删除成功');
					
				}, function(error) {
					console.error('文件删除失败:' + error.code);
				});
			});
		})
}

uniapp获取设备剩余存储空间的方法

function getStorage() {
    const environment = plus.android.importClass("android.os.Environment");
    const statFs = plus.android.importClass("android.os.StatFs");
    plus.android.importClass("java.io.File");
    const Files = environment.getDataDirectory();
    const StatFs = new statFs(Files.getPath());
    const blockAva = parseFloat(StatFs.getAvailableBlocks());
    const blockSize = parseFloat(StatFs.getBlockSize());
    const internalMemSize = blockSize * blockAva;
    // 自己根据单位来计算结果,本示例计算的是以为G单位的剩余容量
    const freeSize = internalMemSize / 1024 / 1024 / 1024;
    return freeSize.toFixed(2) + 'G'
}

读取本地文件夹下的文件

注意:如果不用箭头函数的话,在plus.的方法里面是不能使用this访问外部变量的,一定一定要使用箭头函数处理。

		readFile() {
			const folderPath = 'file://storage/sdcard0/Android/data/io.dcloud.HBuilder/files/';
			this.aFileList = [];
			plus.io.resolveLocalFileSystemURL(
				folderPath, //指定的目录
				(entry) => {
					var directoryReader = entry.createReader(); //获取读取目录对象
					directoryReader.readEntries(
						(entries) => { //返回的是指定文件夹下的文件列表
							this.aFileList = entries
							this.aFileList.forEach(i => {
								if (/\./.test(i.name)) {
									this.list.push({
										name: i.name
									})
								}
							})
						},
						(err) => {
							console.log("访问目录失败");
						});
				},
				(err) => {
					console.log("访问指定目录失败:" + err.message);
				});
		},

相关文章:

  • Windows11+PyCharm利用MMSegmentation训练自己的数据集保姆级教程
  • Springboot 中如何使用Sentinel
  • fastadmin 接口请求提示跨域
  • Windows系统安装搭建悟空crm客户管理系统 教程
  • SpringBoot+Dubbo+zookeeper 急速入门案例
  • Python爬虫实战:获取笔趣阁图书信息,并做数据分析
  • grep如何排除多个目录?
  • 网易易盾接入DeepSeek,数字内容安全“智”理能力全面升级
  • 2-使用wifidog实现portal
  • Java进阶篇之NIO基础
  • MyBatis常见知识点
  • 荣耀手机Magic3系列、Magic4系列、Magic5系列、Magic6系列、Magic7系列详情对比以及最新二手价格预测
  • vue elementui select下拉库组件鼠标移出时隐藏下拉框
  • C++ 常用的设计模式
  • 实时云渲染:驱动XR技术产业化腾飞的核心引擎
  • C语言中常见关键字(static,extern)
  • <论文>DeepSeek-R1:通过强化学习激励大语言模型的推理能力(深度思考)
  • TCP的拥塞控制
  • Postman如何汉化(保姆级教程)
  • Web渗透测试自学习资料超级大全 流程资料文档 涵盖OWASP Top Ten 漏洞 持续更新 ............
  • 中材建设有限公司招标网站/求职seo推荐
  • 网站公司怎么做运营/网络营销步骤
  • 东莞网站关键字/9 1短视频安装
  • 网站承建商有哪些/怎样制作网页新手自学入门
  • 老王传奇新开网站/百度关键词推广条件
  • 县局网站建设招标/成都网站改版优化