uniapp 使用5+API实现文件的读取,写入功能,实现数据离线持久化

开发关于uniapp的离线项目时使用到了文件的读取和写入功能,就找到5+API中的IO模块
官方文档:https://www.html5plus.org/doc/zh_cn/io.html

前提:

准备好一个js文件,将文件的读取和写入方法都放进去,使用的时候页面中引用文件即可。

// 读取json文件
function getJsonData(path) { //path:路径
	//文件读写是一个异步请求 用promise包起来方便使用时的async+await
	return new Promise(resolve => { 
		plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, fs => { //请求文件系统
				fs.root.getFile(
					path,  //请求文件的地址
					{
						create: true //当文件不存在时创建
					}, fileEntry => {
						fileEntry.file(function(file) {
							//new一个可以用来读取文件的对象fileReader
							let fileReader = new plus.io.FileReader(); 
							fileReader.readAsText(file, "utf-8"); //读文件的格式
							fileReader.onerror = e => { //读文件失败
								console.log("获取文件失败", fileReader.error);
								plus.nativeUI.toast("获取文件失败,请重启应用", {
									background: "#ffa38c",
									duration: 2000
								});
								return;
							};
							fileReader.onload = e => { //读文件成功
								console.log("读取文件成功");
								let txtData = e.target.result;
								// console.log(txtData);
								//回调函数内的值想返回到函数外部  就用promise+resolve来返回出去
								resolve(txtData); 
							};
						});
					}, error => {
						console.log("2新建获取文件失败", error);
						plus.nativeUI.toast("获取文件失败,请重启应用", {
							background: "#ffa38c",
							duration: 2000
						});
						return;
					});
			},
			e => {
				console.log("1请求文件系统失败", e.message);
				plus.nativeUI.toast("请求系统失败,请重启应用", {
					background: "#ffa38c",
					duration: 2000
				});
				return;
			}
		);
	});
};
// 写入josn文件
function changeData(path, seek, writeData) { //参数1:上传路径,参数2:seek方法可设置文件操作指定位置,参数3:写入的json数据
	return new Promise(resolve => {
		plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, fs => {
			fs.root.getFile(path, {
					create: true
				}, fileEntry => {
					fileEntry.file(file => {
						fileEntry.createWriter(writer => {
								plus.nativeUI.showWaiting("正在保存信息");
								writer.seek(seek); //覆盖文件
								const writeDataTemp = JSON.stringify(writeData, null,
									"\r").replace(/[\r]/g, "");
								writer.write(writeDataTemp); // 整个文件重写
								writer.onerror = function() {
									console.log("4写入文件失败", writer.error.message);
									plus.nativeUI.closeWaiting();
									plus.nativeUI.toast("修改信息失败,请重新操作", {
										background: "#ffa38c",
										duration: 2000
									});
									return;
								};
								writer.onsuccess = function() { //填写文件成功
									plus.nativeUI.closeWaiting();
									plus.nativeUI.toast("修改信息成功", {
										background: "rgba(255, 255, 255, 0.6)",
										duration: 2000
									});
									resolve("1");
								};
							},
							error => {
								console.log("3创建creactWriter失败", error);
								plus.nativeUI.toast("保存文件失败,请重新操作", {
									background: "#ffa38c",
									duration: 2000
								});
								return;
							});
					});
				},
				error => {
					console.log("2获取文件失败", error);
					plus.nativeUI.toast("保存文件失败,请重新操作", {
						background: "#ffa38c",
						duration: 2000
					});
					return;
				}
			);
		}, e => {
			console.log("1请求文件系统失败", e.message);
			plus.nativeUI.toast("请求系统失败,请重新操作", {
				background: "#ffa38c",
				duration: 2000
			});
			return;
		});
	});
}
/**
 * 储存文件到指定的地址:把一个文件移动到另外一个位置 剪切文件 重命名文件
 * @param {String} url				 	新的地址 _doc/ 开头
 * @param {String} file                	原文件地址
 * @param {String} newfilename 			新的文件名
 */
async function saveFile(url, file, newfilename) {
	let c = await creatDirs(url)
	let isokm = moveDirectyOrFile(file, url + "/", newfilename);
	return isokm
}
//循环创建目录 在本地系统中定义好路径,确保路径存在才行
async function creatDirs(url) {
	let urllist = url.split("/");
	console.log(urllist)
	//创建文件夹
	let u = "";
	for (let i = 0; i < urllist.length - 1; i++) {
		let j = i;
		if (i == 0) {
			u = urllist[i];
		} else {
			u = u + "/" + urllist[i];
		}
		console.log(i + "-------------------")
		console.log(u)
		console.log(urllist[j + 1])
		await CreateNewDir(u, urllist[j + 1]);
	}
}
//重命名目录或文件名
function moveDirectyOrFile(srcUrl, dstUrl, newName) { //srcUrl需要移动的目录或文件,dstUrl要移动到的目标目录(父级)
	plus.io.resolveLocalFileSystemURL(srcUrl, function(srcEntry) {
		//console.log(111)
		plus.io.resolveLocalFileSystemURL(dstUrl, function(dstEntry) {
			//console.log(222)
			if (srcEntry.isDirectory) {
				//console.log(33)
				srcEntry.moveTo(dstEntry, newName, function(entry) {
					//console.log("New Path: " + entry.fullPath);
					return true;
				}, function(e) {
					return e;
					//console.log(e.message);
				});
			} else {
				srcEntry.moveTo(dstEntry, newName, function(entry) {
					//console.log("New Path: " + entry.fullPath);
					return true;
				}, function(e) {
					return e;
					//console.log(e.message);
				});
			}
		}, function(e) {
			uni.showToast({
				title: '获取目标目录失败:' + e.message,
				duration: 2000,
				icon: 'none'
			});
		});
	}, function(e) {
		uni.showToast({
			title: '获取目录失败:' + e.message,
			duration: 2000,
			icon: 'none'
		});
	});
}

//创建一个新目录
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'
			});
		});
	})
}
/**
 * 复制文件
 * @param {String} url        文件地址,文件路径,最好是相对路径 url:"_doc/...."  _doc开头
 * @param {String} newUrl     目标目录,最好是相对路径 url:"_doc/...."  _doc开头
 * @param {String} newName    拷贝后的文件名称,默认为原始文件名称
 */
function copyFileTo(url, newUrl, dirName, newName) {
	if (url.length >= 7 && "file://" == url.substring(0, 7)) {
		url = url.substring(7)
	}
	let tempUrl = url.substring(0, url.lastIndexOf('/'));
	let addUrl = newUrl + '/' + dirName;
	console.log(addUrl, tempUrl)
	if (addUrl == tempUrl) {
		return url;
	}
	console.log(newUrl, dirName, newName)
	return new Promise((resolve, reject) => {
		plus.io.resolveLocalFileSystemURL(url, async (entry) => {
			if (entry.isFile) {
				let c = await CreateNewDir(newUrl, dirName)
				let u = await getDirsys(addUrl)
				entry.copyTo(u, newName, en => {
					resolve(en.fullPath);
				}, e => {
					console.log(e);
					reject('错误:复制时出现错误')
					uni.showModal({
						title: "错误",
						content: "复制时出现错误"
					})
				})
			} else {
				reject('错误:路径必须是文件')
				uni.showModal({
					title: "错误",
					content: "路径必须是文件"
				})
			}
		}, (e) => {
			console.log(e);
			reject(e)
			uni.showModal({
				title: "错误",
				content: "打开文件系统时出错"
			})
		});
	})
}
//获取目录对象
function getDirsys(url) {
	return new Promise((resolve, reject) => {
		plus.io.resolveLocalFileSystemURL(url, (entry) => {
			resolve(entry)
		}, (e) => {
			reject(e)
			console.log(e);
		});
	})
}
//将这些方法暴露出去
export {
	getJsonData,
	changeData,
	saveFile,
	creatDirs,
	moveDirectyOrFile,
	copyFileTo,
	getDirsys,
};

首先,准备好后台给你的json文件格式的文件,在项目需要获取数据的时候,引入js文件,进行数据读取

 //导出数据:显示Upload文件夹的json数据
 import { getJsonData, changeData } from '../../common/task.js';
 export default {
	data() {
		return {
			taskList: [],
		};
	},
	onShow() {
		console.log('onShow');	
		if (process.env.NODE_ENV === 'development') {
			// 测试数据这样写保险点
			this.getSavedData()
			return
		}
	},
	methods: {
		async getSavedData(){//文件读写是一个异步请求 用promise包起来方便使用时的async+await
			const pathUrl = 'config/task.json';
			console.log("----dataJson-----00000--");
			
			const dataJson = await getJsonData(pathUrl);// 1.获取当前任务json数据,序列化json数据
			// 2.将数据反序列化为对象进行循环,然后赋值给全局对象供全局对象
			console.log("----dataJson-------", JSON.parse(dataJson));
			
			// 网络请求获取json数据 并保存到本地文本文件中 路径为:pathUrl
			uni.request({
				url:'http://192.168.123.204:8000/ages.json',
				success: (res) => {
					console.log("----res--json------");
					console.log(res);
					changeData(pathUrl, 0, res); //参数:保存路径,0,全局变量数据
				}
			})
		},
	}
}

其次,将修改后的数据再重新写入json数据里,更换原来的json文件(这里需要项目中的全局变量配合进行数据更换)

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 下面是一个简单的Spring Boot + Spring Batch + Hibernate + Quartz的批量读文件数据的例子: 1. 创建Spring Boot项目 首先,我们需要创建一个Spring Boot项目。可以使用Spring Initializr或者手动创建一个Maven项目。在pom.xml文件中添加相关依赖: ```xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-batch</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency> </dependencies> ``` 2. 创建Job 接下来,我们要创建一个Job。Job是一个执行具体任务的实体,可以包含一个或多个Step。 ```java @Configuration public class JobConfiguration { @Autowired private JobBuilderFactory jobBuilderFactory; @Autowired private StepBuilderFactory stepBuilderFactory; @Autowired private DataSource dataSource; @Bean public FlatFileItemReader<Person> reader() { FlatFileItemReader<Person> reader = new FlatFileItemReader<>(); reader.setResource(new ClassPathResource("persons.csv")); reader.setLineMapper(new DefaultLineMapper<Person>() {{ setLineTokenizer(new DelimitedLineTokenizer() {{ setNames(new String[]{"firstName", "lastName", "email"}); }}); setFieldSetMapper(new BeanWrapperFieldSetMapper<Person>() {{ setTargetType(Person.class); }}); }}); return reader; } @Bean public PersonItemProcessor processor() { return new PersonItemProcessor(); } @Bean public JpaItemWriter<Person> writer() { JpaItemWriter<Person> writer = new JpaItemWriter<>(); writer.setEntityManagerFactory(entityManagerFactory().getObject()); return writer; } @Bean public Job importUserJob(JobCompletionNotificationListener listener) { return jobBuilderFactory.get("importUserJob") .incrementer(new RunIdIncrementer()) .listener(listener) .flow(step1()) .end() .build(); } @Bean public Step step1() { return stepBuilderFactory.get("step1") .<Person, Person>chunk(10) .reader(reader()) .processor(processor()) .writer(writer()) .build(); } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource); em.setPackagesToScan("com.example.demo"); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; } private Properties additionalProperties() { Properties properties = new Properties(); properties.setProperty("hibernate.hbm2ddl.auto", "create-drop"); properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect"); return properties; } } ``` Job主要包含以下几个部分: - reader:读取文件中的数据 - processor:处理每一条数据 - writer:将数据写入数据库 - step:定义一个Step - job:定义一个Job,包含一个或多个Step 3. 创建任务调度 接下来,我们需要创建一个任务调度,使用Quartz来实现。我们可以在应用启动时,自动启动任务调度。以下是一个简单的任务调度配置: ```java @Configuration public class SchedulerConfiguration { @Autowired private JobLauncher jobLauncher; @Autowired private Job importUserJob; @Bean public JobDetail jobDetail() { return JobBuilder.newJob().ofType(SpringJobAdapter.class) .storeDurably() .withIdentity("importUserJob") .withDescription("Invoke Spring batch from quartz") .build(); } @Bean public Trigger trigger(JobDetail job) { SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(60) .repeatForever(); return TriggerBuilder.newTrigger().forJob(job) .withIdentity("importUserTrigger") .withDescription("Simple trigger") .withSchedule(scheduleBuilder) .build(); } @Bean public Scheduler scheduler(Trigger trigger, JobDetail job) throws SchedulerException { SchedulerFactory factory = new StdSchedulerFactory(); Scheduler scheduler = factory.getScheduler(); scheduler.scheduleJob(job, trigger); scheduler.setJobFactory(springBeanJobFactory()); scheduler.start(); return scheduler; } @Bean public SpringBeanJobFactory springBeanJobFactory() { return new AutowiringSpringBeanJobFactory(); } public class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware { private transient AutowireCapableBeanFactory beanFactory; @Override public void setApplicationContext(ApplicationContext context) { beanFactory = context.getAutowireCapableBeanFactory(); } @Override protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { final Object job = super.createJobInstance(bundle); beanFactory.autowireBean(job); return job; } } } ``` 这里我们使用了Spring JobAdapter来将Spring Batch的Job包装成Quartz Job。同时,我们也定义了一个Simple Trigger,每隔60秒执行一次。 4. 编写数据处理逻辑 最后,我们需要编写具体的数据处理逻辑。这里我们简单的将读取到的Person数据插入到数据库中。以下是一个简单的数据处理类: ```java public class PersonItemProcessor implements ItemProcessor<Person, Person> { @Override public Person process(Person person) throws Exception { return person; } } ``` 5. 创建数据模型 在这个例子中,我们需要处理的数据是Person,我们需要创建一个Person类来描述数据模型: ```java @Entity public class Person { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String firstName; private String lastName; private String email; // getter and setter } ``` 6. 创建文件 最后,我们需要创建一个csv文件,用于存储测试数据文件名为persons.csv,内容如下: ```csv firstName,lastName,email John,Doe,john.doe@example.com Jane,Doe,jane.doe@example.com Bob,Smith,bob.smith@example.com Alice,Smith,alice.smith@example.com ``` 7. 运行程序 完成以上步骤后,我们可以运行程序。当程序运行时,任务调度会定时执行任务,将csv文件中的数据插入到数据库中。 总的来说,这是一个简单的Spring Boot + Spring Batch + Hibernate + Quartz的批量读文件数据的例子。通过这个例子,可以熟悉Spring Batch的基本使用方法,并了解如何使用Quartz实现任务调度。 ### 回答2: Spring Boot是一种快速开发应用程序的框架,Spring Batch是Spring Boot的子项目,用于处理大量数据的批量处理任务。在这个用例中,我们可以使用Spring Boot、Spring Batch、Hibernate和Quartz来实现简单的批量读取文件写入数据。 首先,我们需要在Spring Boot项目中引入Spring Batch和Hibernate的依赖。然后,创建一个包含读取文件写入数据的批处理任务。 使用Spring Batch的ItemReader接口从文件中逐行读取数据。你可以使用FlatFileItemReader类并配置文件路径、行解析器等属性来实现这一步骤。 接下来,使用Hibernate的Entity类和Repository来定义和操作数据表。根据业务需求,创建一个实体类并使用JPA注解配置。然后,创建一个Repository接口,用于查询和保存数据。 在批处理任务的写入步骤中,我们可以使用Hibernate的Session来保存数据。通过调用Repository的save方法,将读取到的数据写入数据库。 最后,使用Quartz来触发批处理任务。可以配置Quartz的定时任务,按照一定的时间间隔或特定时间点触发批处理任务的执行。 在整个过程中,我们需要根据实际需求进行配置和开发,确保数据的正确读取写入。可以使用Spring Boot自带的自动配置或者手动配置来实现以上功能。 综上所述,我们可以使用Spring Boot、Spring Batch、Hibernate和Quartz来实现简单的批量读取文件写入数据的用例。这个用例可以用来处理大量数据的批处理任务,实现数据的批量处理和定时执行。 ### 回答3: Spring Boot是一个用于创建独立的、基于Spring的生产级应用程序的框架。它简化了Spring应用程序的配置和部署过程,并提供了一套强大的开发工具和约定,使开发人员能够更快地构建应用程序。 Spring Batch是一个用于批量处理的框架。它提供了一种简单而强大的方式来处理大量的数据,并允许我们以可靠的方式处理失败和重试。它还提供了许多批处理作业开发和管理的功能,如读取数据源、处理数据并将结果写入目标数据源。 Hibernate是一个用于对象关系映射(ORM)的框架。它简化了Java应用程序与关系数据库之间的交互,并提供了一个对象导向的方式来操作数据。它提供了一种将对象持久化数据库中的简单方式,并为开发人员提供了一套强大的查询语言(HQL)来执行复杂的数据库查询操作。 Quartz是一个用于任务调度的框架。它允许我们按照预定的时间间隔或时间短划进行任务调度。它还提供了一种强大的任务管理和监控机制,可以处理并发任务,并支持持久化任务调度信息。 下面是一个简单的批量读取文件并将数据写入数据库的示例: 1. 使用Spring Boot创建一个新的Web应用程序。 2. 导入Spring Batch、Hibernate和Quartz的依赖项。 3. 创建一个包含文件读取数据处理和数据写入的Spring Batch作业。 4. 在作业中使用Hibernate作为数据读取文件的内容。 5. 配置Quartz来调度作业的执行。 6. 在作业中实现一个写入数据库的处理器。 7. 配置Hibernate来将处理后的数据写入数据库。 8. 运行应用程序并观察任务按计划执行,并且文件中的数据被正确地写入数据库。 这个示例演示了如何使用Spring Boot、Spring Batch、Hibernate和Quartz来构建一个简单的批量处理应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Nick5683

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值