元服务——json文件处理
2024-11-30 15:09:44
17次阅读
0个评论
最后修改时间:2024-11-30 16:00:22
先创建元服务
需要手动登录,打开浏览器后同意登录
1、json权限获取
找到string.json添加一段代码
entry\src\main\resources\base\element\string.json
找到module.json5添加一段代码
entry\src\main\module.json5
2、写入文件操作
需要的包:
import { fileIo } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { buffer, List } from '@kit.ArkTS';
写入函数:
createFile(){
// 获取应用文件路径
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
// 新建并打开文件
let file = fileIo.openSync(filesDir + this.fileName, fileIo.OpenMode.WRITE_ONLY | fileIo.OpenMode.CREATE);
// 将集合转换成json序列化对象存储到文件中
let writeLen = fileIo.writeSync(file.fd, "写入的信息");
console.info("字符串长度: " + writeLen);
// 从文件读取一段内容
console.info(filesDir)
// 关闭文件
fileIo.closeSync(file);
}
完整Index:
import { authentication } from '@kit.AccountKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { fileIo } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { buffer, List } from '@kit.ArkTS';
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
@State fileName:string="/test.txt";
aboutToAppear(): void {
this.createFile();
console.info("初始化完毕")
}
createFile(){
// 获取应用文件路径
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
// 新建并打开文件
let file = fileIo.openSync(filesDir + this.fileName, fileIo.OpenMode.WRITE_ONLY | fileIo.OpenMode.CREATE);
// 将集合转换成json序列化对象存储到文件中
let writeLen = fileIo.writeSync(file.fd, "写入的信息");
console.info("字符串长度: " + writeLen);
// 从文件读取一段内容
console.info(filesDir)
// 关闭文件
fileIo.closeSync(file);
}
build() {
RelativeContainer() {
Text(this.message)
.id('HelloWorld')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
}
.height('100%')
.width('100%')
}
}
运行之后,会在log日志中看到初始化完毕
并且在根目录(我的在D盘)会自动创建test.txt写入信息
3、读取文件操作
Index中添加代码:
readFile():string{
let context = getContext(this) as common.UIAbilityContext;
if (!context) {
console.info("无法获取有效的上下文");
return "";
}
let filesDir = context.filesDir;
// 新建并打开文件
let file = fileIo.openSync(filesDir + this.fileName, fileIo.OpenMode.READ_ONLY|fileIo.OpenMode.CREATE);
let bufferSize = 1024;
let arrayBuffer = new ArrayBuffer(bufferSize);
class Option {
public offset: number = 0;
public length: number = bufferSize;
}
let option = new Option();
let content: string = "";
let readLen: number=0;
do {
// 读取文件内容到数组缓冲区
readLen = fileIo.readSync(file.fd, arrayBuffer, option);
if (readLen > 0) {
let buf = buffer.from(arrayBuffer, 0, readLen);
content += buf.toString();
// 更新下一次读取的偏移量,继续从文件后续位置读取
option.offset += readLen;
}
} while (readLen === bufferSize);//判断+赋值
console.info("内容是:"+content)
// 关闭文件
fileIo.closeSync(file);
return content;
}
可以将build中文本标签改成按钮
build() {
RelativeContainer() {
Button(this.message)
.id('HelloWorld')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
}).onClick(()=>{
console.info(this.readFile())
})
}
.height('100%')
.width('100%')
}
}
点击按钮后,可以将信息显示在log中
序列化
先在entry\src\main\etc下创建 “model” 文件夹 创建Orders模型:
export class Orders{
/**
* 排名
*/
public getTime:string = "";
public no :number = 0;
public score :number = 0;
public name:string = "";
}
将以下代码替换Index.json中部分
createFile(){
// 获取应用文件路径
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
// 新建并打开文件
let file = fileIo.openSync(filesDir + this.fileName, fileIo.OpenMode.WRITE_ONLY | fileIo.OpenMode.CREATE);
//字符串序列化
let o :Orders = new Orders()
o.no = 1;
o.name = "刘德华";
o.getTime = "1998-10-10 06:06:06"
o.score = 98 ;
//反序列化
let writeLen = fileIo.writeSync(file.fd,JSON.stringify(o));
console.info("字符串长度: " + writeLen);
// 从文件读取一段内容
console.info(filesDir)
// 关闭文件
fileIo.closeSync(file);
}
会看到编译完成后,点击 “Hello World” 按钮,log更新的日志 效果:
同样test.txt中日志也会更新
反序列化
示例一
Index上方添加调用语句: @State info : Orders|null = null;
读取代码下方单独写一下反序列化代码:
//将字符串反序列化
backModel(){
this.info = JSON.parse(this.readFile())
}
在build中添加文本:
Text(){
Span(this.info?.no.toString())
Span(this.info?.name.toString())
Span(this.info?.getTime.toString())
Span(this.info?.score.toString())
}
完整Index
import { authentication } from '@kit.AccountKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { fileIo } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { buffer, List } from '@kit.ArkTS';
import { Orders } from '../model/Orders';
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
@State fileName:string="/test.txt";
@State info : Orders|null = null;
aboutToAppear(): void {
this.createFile();
console.info("初始化完毕")
this.backModel()
}
createFile(){
// 获取应用文件路径
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
// 新建并打开文件
let file = fileIo.openSync(filesDir + this.fileName, fileIo.OpenMode.WRITE_ONLY | fileIo.OpenMode.CREATE);
//字符串序列化
let o :Orders = new Orders()
o.no = 1;
o.name = "刘德华";
o.getTime = "1998-10-10 06:06:06"
o.score = 98 ;
//反序列化
let writeLen = fileIo.writeSync(file.fd,JSON.stringify(o));
console.info("字符串长度: " + writeLen);
// 从文件读取一段内容
console.info(filesDir)
// 关闭文件
fileIo.closeSync(file);
}
readFile():string{
let context = getContext(this) as common.UIAbilityContext;
if (!context) {
console.info("无法获取有效的上下文");
return "";
}
let filesDir = context.filesDir;
// 新建并打开文件
let file = fileIo.openSync(filesDir + this.fileName, fileIo.OpenMode.READ_ONLY|fileIo.OpenMode.CREATE);
let bufferSize = 1024;
let arrayBuffer = new ArrayBuffer(bufferSize);
class Option {
public offset: number = 0;
public length: number = bufferSize;
}
let option = new Option();
let content: string = "";
let readLen: number=0;
do {
// 读取文件内容到数组缓冲区
readLen = fileIo.readSync(file.fd, arrayBuffer, option);
if (readLen > 0) {
let buf = buffer.from(arrayBuffer, 0, readLen);
content += buf.toString();
// 更新下一次读取的偏移量,继续从文件后续位置读取
option.offset += readLen;
}
} while (readLen === bufferSize);//判断+赋值
console.info("内容是:"+content)
// 关闭文件
fileIo.closeSync(file);
return content;
}
//将字符串反序列化
backModel(){
this.info = JSON.parse(this.readFile())
}
build() {
RelativeContainer() {
Text(){
Span(this.info?.no.toString())
Span(this.info?.name.toString())
Span(this.info?.getTime.toString())
Span(this.info?.score.toString())
}
Button(this.message)
.id('HelloWorld')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
}).onClick(()=>{
console.info(this.readFile())
})
}
.height('100%')
.width('100%')
}
}
效果:
示例二
将以下代码替换build后文本部分:
Column() {
ForEach(this.info,(o:Orders,Index)=> {
Column() {
Text(o.no.toString())
Text(o.name.toString())
Text(o.getTime.toString())
Text(o.score.toString())
}
})
将以下代码替换示例一调用语句: @State info : Array<Orders>|null = null;
示例一的createFile部分的反序列化代码中 “o” 替换为 “arr” : let writeLen = fileIo.writeSync(file.fd,JSON.stringify(arr));
完整Index:
import { authentication } from '@kit.AccountKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { fileIo } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { buffer, List } from '@kit.ArkTS';
import { Orders } from '../model/Orders';
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
@State fileName:string="/test.txt";
@State info : Array<Orders>|null = null;
aboutToAppear(): void {
this.createFile();
console.info("初始化完毕")
this.backModel()
}
createFile(){
// 获取应用文件路径
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
// 新建并打开文件
let file = fileIo.openSync(filesDir + this.fileName, fileIo.OpenMode.WRITE_ONLY | fileIo.OpenMode.CREATE);
//字符串序列化
let arr: Array<Orders> = new Array<Orders>();
for (let index = 0; index < 10; index++) {
let o:Orders = new Orders();
o.no = index + 1;
o.name = "刘德华"+index;
o.getTime = "1998-10-10 06:06:0"+index;
o.score = 80+index;
arr.push(o)
}
//反序列化
let writeLen = fileIo.writeSync(file.fd,JSON.stringify(arr));
console.info("字符串长度: " + writeLen);
// 从文件读取一段内容
console.info(filesDir)
// 关闭文件
fileIo.closeSync(file);
}
readFile():string{
let context = getContext(this) as common.UIAbilityContext;
if (!context) {
console.info("无法获取有效的上下文");
return "";
}
let filesDir = context.filesDir;
// 新建并打开文件
let file = fileIo.openSync(filesDir + this.fileName, fileIo.OpenMode.READ_ONLY|fileIo.OpenMode.CREATE);
let bufferSize = 1024;
let arrayBuffer = new ArrayBuffer(bufferSize);
class Option {
public offset: number = 0;
public length: number = bufferSize;
}
let option = new Option();
let content: string = "";
let readLen: number=0;
do {
// 读取文件内容到数组缓冲区
readLen = fileIo.readSync(file.fd, arrayBuffer, option);
if (readLen > 0) {
let buf = buffer.from(arrayBuffer, 0, readLen);
content += buf.toString();
// 更新下一次读取的偏移量,继续从文件后续位置读取
option.offset += readLen;
}
} while (readLen === bufferSize);//判断+赋值
console.info("内容是:"+content)
// 关闭文件
fileIo.closeSync(file);
return content;
}
//将字符串反序列化
backModel(){
this.info = JSON.parse(this.readFile())
}
build() {
Column() {
ForEach(this.info,(o:Orders,Index)=> {
Column() {
Text(o.no.toString())
Text(o.name.toString())
Text(o.getTime.toString())
Text(o.score.toString())
}
})
Button(this.message)
.id('HelloWorld')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
}).onClick(()=>{
console.info(this.readFile())
})
}
.height('100%')
.width('100%')
}
}
效果:
00