H5关于手机本地系统文件的写入、读取及删除

一、写入文件

//isAppend为true时:追加内容, false时:重新写入
function saveData(news, callback, isAppend) {
	callback = callback || mui.noop;
	plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
		// fs.root是根目录操作对象DirectoryEntry
		fs.root.getFile('_doc/data.json', {
			create: true
		}, function(fileEntry) {
			fileEntry.createWriter(function(writer) {
				writer.onwrite = function(e) {
					console.log("Write data success!");
				};
				var data = JSON.stringify(news);
                
				if(isAppend) {
					try {
						writer.seek(writer.length);
					} catch(e) {
						console.log("file doesn't exist!");
					}
				}
				writer.write(data);
				callback({
					state: 1,
					message: "保存数据成功!"
				});
			}, function(e) {
				callback({
					state: -1,
					message: e.message
				});
			});
		});
	}, function(e) {
		callback({
			state: -1,
			message: e.message
		});
	});
};

二、读取文件

function readFile(callback) {
	callback = callback || mui.noop;
	plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
		// fs.root是根目录操作对象DirectoryEntry
		fs.root.getFile('_doc/data.json', {
			create: false
		}, function(fileEntry) {
			fileEntry.file(function(file) {
				console.log(file.size + '--' + file.name);
				var fileReader = new plus.io.FileReader();
				fileReader.readAsText(file, 'utf-8');
				fileReader.onloadend = function(evt) {
					var news = [];
					var result = evt.target.result;
					if(result != "")
					callback({state:1,message:"读取成功!",data:result});
				}
			});
		});
	}, function(e) { 
		callback({
			state: -1,
			message: e.message
		});
	});
}

三、删除文件

var dirPath = '_doc/devData/';
plus.io.resolveLocalFileSystemURL(dirPath, function(entry) {
	//读取这个目录对象    
	var directoryReader = entry.createReader();
	//读取这个目录下的所有文件    
	directoryReader.readEntries(function(entries) {
		//如果有才操作    
		if(entries.length > 0) {
			//删除目录将会删除其下的所有文件及子目录 不能删除根目录,如果操作删除根目录  
			//将会删除目录下的文件及子目录,不会删除根目录自身。 删除目录成功通过succesCB  
			//回调返回,失败则通过errorCB返回。  
			entry.removeRecursively(function(entry) {
				console.log('删除成功回调')
				//删除成功回调    
			}, function(e) {
				//错误信息    
				console.log(e.message + ' ?!')
			})
		}
	})
})

 

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值