HarmonyOS 鸿蒙Next 如何在ArkTS中请求下载在本地的sqlite文件呢
HarmonyOS 鸿蒙Next 如何在ArkTS中请求下载在本地的sqlite文件呢
这是我手动上传的sqlite文件。我的目的是要获取其中的表的信息。
我原本是想通过将文件转移到沙盒文件中,再通过关系型数据库去访问的,但是失败了。这是我转移文件的代码。
saveFileToCache(file:string, dbName:string) {
let cFile = getContext(this).getApplicationContext().databaseDir + "/rdb/" + dbName
let cacheFile = fs.openSync(cFile, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
fs.write(cacheFile.fd, file).then((writeLen: number) => {
console.info("write data to file succeed and size is:" + writeLen);
ToastUtil.showToast("write data to file succeed and size is:" + writeLen)
}).catch((err: BusinessError) => {
console.error("write data to file failed with error message: " + err.message + ", error code: " + err.code);
}).finally(() => {
fs.closeSync(cacheFile);
});
}
文件路径是:/data/storage/el2/database/rdb/smart.db
然后我还想用附加数据库进行附加,但是提示路径无效,求大佬!!!
6 回复
raw文件拷贝到沙箱参考demo:
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import fs from '@ohos.file.fs'
export function myRawfileCopy(context: common.UIAbilityContext) {
context.resourceManager.getRawFileContent("aaa.txt", (err: BusinessError, data: Uint8Array) => {
if (err != null) {
console.error(`open aaa.txt failed: ${err.message}`)
} else {
let buffer = data.buffer
let sanboxPath = context.getApplicationContext().databaseDir + "/rdb";
console.log('myRawfileCopy path' + sanboxPath)
let filePath = sanboxPath + "/aaa.txt"
// 创建沙箱目录
if (!fs.accessSync(sanboxPath)) {
fs.mkdirSync(sanboxPath);
}
let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE)
try {
fs.writeSync(file.fd, buffer) // 拷贝文件到沙箱,为了简便,这里是直接getrawfilecontent然后写入,当文件过大时内存压力会很大,如需优化,可通过buffer进行读取
fs.close(file.fd)
// 把沙箱中的文件第一行读出来,验证是否拷贝成功;(fs.readFileSync 方法读取整个文件)
let data = fs.readTextSync(filePath);
console.log('myRawfileCopy success ' + data)
} catch (err) {
console.log('myRawfileCopy error')
}
}
})
}
更多关于HarmonyOS 鸿蒙Next 如何在ArkTS中请求下载在本地的sqlite文件呢的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
试了一下,失败了,
有异常原因和日志之类的吗,
已经解好了,多谢您!
在HarmonyOS鸿蒙Next中,使用ArkTS请求下载并存储本地的SQLite文件,可以通过以下步骤实现:
- 网络请求:使用
@ohos.net.http
模块发起HTTP请求,获取SQLite文件。 - 文件存储:使用
@ohos.file.fs
模块将下载的文件保存到本地。 - 数据库操作:使用
@ohos.data.relationalStore
模块操作SQLite数据库。
示例代码:
import http from '@ohos.net.http';
import fs from '@ohos.file.fs';
import relationalStore from '@ohos.data.relationalStore';
async function downloadAndStoreSQLite(url: string, localPath: string) {
const httpRequest = http.createHttp();
const response = await httpRequest.request(url);
await fs.writeFile(localPath, response.result);
const rdbStore = await relationalStore.getRdbStore({ name: 'myDatabase.db' });
// 进一步操作数据库
}
确保在config.json
中声明必要的权限,如ohos.permission.INTERNET
和ohos.permission.WRITE_USER_STORAGE
。