uniapp与NativeJs实现读取安卓本地文件

目前亲测可用于安卓设备,读取本地txt、json等文件。

一、封装读取方法

readJsonByFile(fileNamePath) {
				let that = this;
				// 只能用于安卓 导入java类
				const File = plus.android.importClass('java.io.File')
				const BufferedReader = plus.android.importClass('java.io.BufferedReader')
				const FileReader = plus.android.importClass('java.io.FileReader')
				const FileWriter = plus.android.importClass('java.io.FileWriter')
				// 安卓11以下 /sdcard/自己的文件夹/1.txt
				// 安卓11 建议用 /storage/emulated/0/Download/自己的文件夹/1.txt
				// 读取txt文件 readFile ("/sdcard/修止符/配置.json")
				const readFile = (fileName) => {
					const readFr = new File(fileName)
					try {
						const reader = new BufferedReader(new FileReader(readFr))
						let txt
						let retxt = ''
						let flag = true
						while (flag) {
							txt = reader.readLine() // 读取文件
							if (txt == null) {
								flag = false
								break
							}
							retxt = retxt + txt
						}
						return retxt
					} catch (e) {
						console.log(e)
						return ''
					}
				}
				let json = readFile(fileNamePath);
				return eval("(" + json + ")");
			},

二、使用

传入本地文件地址,即可读取文件内容。

猜你喜欢

转载自blog.csdn.net/start1018/article/details/128589295