繁体   English   中英

Android 从 json 文件 (.txt) 中获取数据

[英]Android get data from json file (.txt)

我有 Json 文件(test.txt),我想从该文件中获取数据到 Android 应用程序。 我的代码是:

private static String url = "file:///AndroidJSONParsingActivity/res/raw/test.txt";

但它不起作用。 我得到的错误是:

error opening trace file: No such file or directory (2)

来人帮帮我? 谢谢!

test.txt文件放入 assets 文件夹

public class Utility {
   public static String readXMLinString(String fileName, Context c) {
      try {
          InputStream is = c.getAssets().open(fileName);
          int size = is.available();
          byte[] buffer = new byte[size];
          is.read(buffer);
          is.close();
          String text = new String(buffer);

          return text;
      } catch (IOException e) {
          throw new RuntimeException(e);
      }
   }
}

然后就可以使用下面的代码获取test.txt

JSONObject json = new JSONObject(Utility.readXMLinString("test.txt",getApplicationContext()));

在 Android 应用资源中有一个使用 JSON 文件的答案

您需要将文件 intro raw 文件夹放入,您可以通过以下方式访问:

getResources().openRawResource(resourceName)

使用getResources().openRawResource(RawResource_id)从 res/raw 文件夹读取文本文件:

 InputStream inputStream = Current_Activity.this.
                            getResources().openRawResource(R.raw.test);
 //put  your code for reading json from text file(inputStream) here

使用以下代码打开存储在原始文件夹中的文件的输入流:

getResources().openRawResource(R.raw.text_file)

请参阅下面的代码,它将解决您的问题。

public void mReadJsonData() {
    try {
        InputStream is = getResources().openRawResource(R.raw.textfilename)
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        String mResponse = new String(buffer);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM