2011-06-14 3 views

답변

97

openRawResource을 참조하십시오. 이런 식으로 뭔가 작업을해야합니다 :

InputStream is = getResources().openRawResource(R.raw.json_file); 
Writer writer = new StringWriter(); 
char[] buffer = new char[1024]; 
try { 
    Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); 
    int n; 
    while ((n = reader.read(buffer)) != -1) { 
     writer.write(buffer, 0, n); 
    } 
} finally { 
    is.close(); 
} 

String jsonString = writer.toString(); 
+1

안드로이드의 String 리소스에 문자열을 넣고 getResources(). getString (R.String.name)을 사용하여 동적으로 사용하려면 어떻게해야합니까? –

+0

나에게 그것은 따옴표 때문에 읽기에는 무시되고 또한 도망 칠 수없는 것처럼 작동하지 않는다. –

+1

[ButterKnife] (http://jakewharton.github.io/butterknife/)를 만들 수있는 방법이 있습니까?) 원시 자원을 바인드합니까? 문자열을 읽는 데 단지 10 줄 이상의 코드를 작성하는 것은 조금 지나치게 과장된 것처럼 보입니다. – Jezor

10

:

원료/
임의의 파일은 원시 형태로 저장합니다. 원시 InputStream을 사용하여 이러한 리소스를 열려면 리소스 ID (R.raw.filename)로 Resources.openRawResource()를 호출합니다.

그러나 원본 파일 이름 및 파일 계층에 대한 액세스가 필요한 경우 res/raw/대신 assets/디렉토리에 일부 리소스를 저장하는 것이 좋습니다. 애셋 내의 파일 /에는 리소스 ID가 주어지지 않으므로 AssetManager 만 사용하여 읽을 수 있습니다.

+1

JSON 파일을 내 앱에 삽입하려는 경우 어디에 넣어야합니까? 자산 폴더 또는 원시 폴더에 있습니까? 감사! – Ricardo

18

나는 자원에서 JSON 파일에서로드, Gson를 사용하여 개체를 만들 @의 kabuko의 답변을 사용 :

package com.jingit.mobile.testsupport; 

import java.io.*; 

import android.content.res.Resources; 
import android.util.Log; 

import com.google.gson.Gson; 
import com.google.gson.GsonBuilder; 


/** 
* An object for reading from a JSON resource file and constructing an object from that resource file using Gson. 
*/ 
public class JSONResourceReader { 

    // === [ Private Data Members ] ============================================ 

    // Our JSON, in string form. 
    private String jsonString; 
    private static final String LOGTAG = JSONResourceReader.class.getSimpleName(); 

    // === [ Public API ] ====================================================== 

    /** 
    * Read from a resources file and create a {@link JSONResourceReader} object that will allow the creation of other 
    * objects from this resource. 
    * 
    * @param resources An application {@link Resources} object. 
    * @param id The id for the resource to load, typically held in the raw/ folder. 
    */ 
    public JSONResourceReader(Resources resources, int id) { 
     InputStream resourceReader = resources.openRawResource(id); 
     Writer writer = new StringWriter(); 
     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(resourceReader, "UTF-8")); 
      String line = reader.readLine(); 
      while (line != null) { 
       writer.write(line); 
       line = reader.readLine(); 
      } 
     } catch (Exception e) { 
      Log.e(LOGTAG, "Unhandled exception while using JSONResourceReader", e); 
     } finally { 
      try { 
       resourceReader.close(); 
      } catch (Exception e) { 
       Log.e(LOGTAG, "Unhandled exception while using JSONResourceReader", e); 
      } 
     } 

     jsonString = writer.toString(); 
    } 

    /** 
    * Build an object from the specified JSON resource using Gson. 
    * 
    * @param type The type of the object to build. 
    * 
    * @return An object of type T, with member fields populated using Gson. 
    */ 
    public <T> T constructUsingGson(Class<T> type) { 
     Gson gson = new GsonBuilder().create(); 
     return gson.fromJson(jsonString, type); 
    } 
} 

이 그것을 사용하기를, 당신은 좋겠 (예는 InstrumentationTestCase에) 다음과 같은 것을 할 :

@Override 
    public void setUp() { 
     // Load our JSON file. 
     JSONResourceReader reader = new JSONResourceReader(getInstrumentation().getContext().getResources(), R.raw.jsonfile); 
     MyJsonObject jsonObj = reader.constructUsingGson(MyJsonObject.class); 
    } 
+0

위대한 :)! 고맙습니다. – nikolaDev

+0

이것을 달성하는 정말 좋은 좋은 재사용 방법. 감사! – speedynomads

+0

당신의 gradle 파일에 의존성을 추가하는 것을 잊지 마세요. {comile.code.gson : gson : 2.8.2 '} – patrics

2
InputStream is = mContext.getResources().openRawResource(R.raw.json_regions); 
          int size = is.available(); 
          byte[] buffer = new byte[size]; 
          is.read(buffer); 
          is.close(); 
          String json = new String(buffer, "UTF-8"); 
16

Kotli n은 이제 Android 용 공식 언어이므로 누군가에게 유용 할 것입니다.

val text = resources.openRawResource(R.raw.your_text_file) 
           .bufferedReader().use { it.readText() } 
관련 문제