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

自定义文件夹以及文件存储位置,放在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(’ ’); 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);

经验分享 程序员 微信小程序 职场和发展