最佳答案
更改位置文件 config.json 并将文件放入“res/raw”文件夹。默认情况下,“raw”文件夹不会在 android proyect 中创建(您必须手动创建)。
总而言之,将你的json文件放在“res/raw/config.json”中。稍后,您可以使用下一个函数在代码中读取此文件:
public String streamToString(InputStream in) {
String l;
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder s = new StringBuilder();
try {
while ((l = r.readLine()) != null) {
s.append(l);
}
} catch (IOException e) {
}
return s.toString();
}
现在,您可以使用前面的函数读取 res 文件夹中的任何文件。在这种情况下,您可以使用下一个代码来读取“config.json”并获取包含文件内容的字符串:
//Function getResources() must be called from a Context Activity or Aplication
InputStream rawResourceConfig = getResources().openRawResource(R.raw.config);
String contentConfig = streamToString(rawResourceConfig);
现在,您已将文件 config.js 中的所有内容作为字符串放入 contentConfig。
最后,您可以使用 GSON 库(例如)将 JSON 字符串转换为 Java 对象。
我希望这是有希望的。
祝你好运。
关于java - 如何通过代码获取我的android应用程序代码根文件夹中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42343786/