效果展示
具体实现
导入第三方库
在build.gradle(:app)的dependencies中加入以下代码引用第三方库
//Json库 implementation 'com.alibaba:fastjson:1.2.76' • 1 • 2
项目结构
assets文件夹位置
assets文件夹需要带小绿标志,否则会找不到文件(可以看下面创建步骤来)
创建步骤
src右键New点击Folder下面的Assets Folder
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
随后会出来这个页面,要选中Change Folder Location,然后接着看下面的图(有具体操作步骤)
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
勾选换路径,这里选择放在src文件夹下,和main为同一级,点击Finish,创建后如果和博主的图标一致即创建成功
代码实现
ReadWriteUtils
package top.gaojc.util; import android.content.Context; import android.content.res.AssetManager; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class ReadWriteUtils{ //从assets资源文件中读取返回字符串 public static String readStringFromAssets(Context context, String fileName) { //通过设备管理对象 获取Asset的资源路径 AssetManager assetManager = context.getAssets(); InputStream inputStream = null; InputStreamReader isr = null; BufferedReader br = null; StringBuffer sb = new StringBuffer(); try { inputStream = assetManager.open(fileName); isr = new InputStreamReader(inputStream); br = new BufferedReader(isr); sb.append(br.readLine()); String line = null; while ((line = br.readLine()) != null) { sb.append("\n" + line); } br.close(); isr.close(); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) { br.close(); } if (isr != null) { isr.close(); } if (inputStream != null) { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } }
Test.java
public class Test{ private int intValue; private String strX; private String strY; //示例代码 private void getAssetsValue() { String bannerConfig = DialogManager.readStringFromAssets(context, "test.json"); if (!TextUtils.isEmpty(bannerConfig)) { try { JSONObject jsonObject = JSON.parseObject(bannerConfig); if (jsonObject.containsKey("intValue")) { intValue = jsonObject.getIntValue("intValue"); } if (jsonObject.containsKey("arr")) { JSONObject jsonObject1 = jsonObject.getJSONObject("arr"); if (jsonObject1.containsKey("strX")) { strX = jsonObject1.getString("strX"); } if (jsonObject1.containsKey("strY")) { strY = jsonObject1.getString("strY"); } } } catch (Throwable e) { e.printStackTrace(); } } } }