鸿蒙开发自定义数据文件的存储以及读取

自定义文件夹以及文件存储位置,放在resources/rawfile文件下面:
在这里插入图片描述
自定义文件夹中文件读取方式有2种:
第一种方式:
String filePath = String.format(“assets/entry/resources/rawfile/api/v1/users/%s”, “page=1.json”)
%s为固定的必须要加
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath );
第二种
数据流的读取
BufferedReader bufferedReader = null;
try {
StringBuilder stringBuilder = new StringBuilder();
if(inputStream == null) {
return null;
}
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String str;
boolean isFirst = true;
while ((str = bufferedReader.readLine()) != null) {
if (isFirst)
isFirst = false;
else
stringBuilder.append(’\n’);
stringBuilder.append(str);
}
return stringBuilder.toString();
} catch (IOException e) {
System.out.print("JsonMockServer: Error opening asset " + name);
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
System.out.print("JsonMockServer: Error closing asset " + name);
}
}
}

第二种方式读取
ResourceManager resourceManager = getApplicationContext().getResourceManager();
RawFileEntry rawFileEntry = resourceManager.getRawFileEntry(fileName);
InputStream inStream=rawFileEntry.openRawFile();
if(inStream=null){
HiLog.error(LABEL_LOG,"inStream
=null");
}else{
HiLog.error(LABEL_LOG,“inStream==”+inStream.toString());
}
int len = 0;
byte[] data = new byte[1024];
while ((len = inStream.read(data)) != -1) {
outputStream.write(data, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
HiLog.error(LABEL_LOG,“FileNotFoundException==”+e.toString());
} catch (IOException e) {
e.printStackTrace();
}

String content=new String(outputStream.toByteArray()

图片流的加载
ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
sourceOptions.formatHint = “image/jpg”;
ImageSource imageSource = ImageSource.create(outputStream.toByteArray(), sourceOptions);
ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
decodingOptions.desiredSize = new Size(0, 0);
decodingOptions.desiredRegion = new Rect(0, 0, 0, 0);
decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);

Image testIcon.setPixelMap(pixelMap);

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值