【问题标题】:Android get data from json file (.txt)Android 从 json 文件 (.txt) 获取数据
【发布时间】:2012-11-26 07:08:16
【问题描述】:

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

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

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

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

有人帮助我吗?谢谢!

【问题讨论】:

    标签: android json string


    【解决方案1】:

    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()));
    

    【讨论】:

      【解决方案2】:

      你有一个答案Using JSON File in Android App Resources

      你需要把文件介绍原始文件夹,你可以访问:

      getResources().openRawResource(resourceName)
      

      【讨论】:

        【解决方案3】:

        使用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
        

        【讨论】:

          【解决方案4】:

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

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

          【讨论】:

            【解决方案5】:

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

            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();
                }
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-12-06
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-11-30
              • 1970-01-01
              相关资源
              最近更新 更多