2017-05-24 2 views
0

에서 JSON 파일에 추가 문자열 내가 다음과 같이 JSON 파일의 목록을 가지고 : 순간 enter image description here복사 및 안드로이드 스튜디오

, T.json 파일이 비어 있습니다. 다른 모든 파일에는 이미 일부 텍스트가 있습니다. 예를 들어,에서

{ 
    "T": [ 

2.Copy 텍스트와 같은 추가 T.json 파일의 시작 1.At STH를

: 내가 필요한 것은 이런 식으로 뭔가를 만드는 것입니다 T_Average.json 및 T_Easy.json이 T.json 파일의 끝에 3.AT 파일

을 T.json이 추가 : 그래서

] }

을 프로그램 실행의 끝에서 나는 필요 내 T.json sth처럼 :

{ 
     "T": [ 
      text from T_Average.json 
      text from T_Easy.json 
     ] 
    } 

그럼 어떻게 파일에 1 단계와 3 단계에서 텍스트를 추가 할 수 있습니까? 다른 파일의 모든 것을 T.json 파일로 복사하려면 어떻게해야합니까?

try(FileWriter fw = new FileWriter("T.json", true); 
    BufferedWriter bw = new BufferedWriter(fw); 
    PrintWriter out = new PrintWriter(bw)) 
{ 
    out.println("the text"); 
    out.println("more text"); 
} catch (IOException e) { 
    //exception handling left as an exercise for the reader 
} 

또는 하나 같이 :

은 이미 다음과 같은 몇 가지 솔루션을 시도

try { 
    String data = " This is new content"; 
    File file = new File(FILENAME); 
    if (!file.exists()) { 
     file.createNewFile(); 
    } 
    fw = new FileWriter(file.getAbsoluteFile(), true); 
    bw = new BufferedWriter(fw); 
    bw.write(data); 
    System.out.println("Done"); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

하지만 모든 시간, fw = new FileWriter()에 부합 후 바로 캐치 절에 점프했다.

한 번 더 : 텍스트를 첫 번째 및 세 번째 단계에서 파일에 추가하려면 어떻게해야합니까? 다른 파일의 모든 것을 T.json 파일로 복사하려면 어떻게해야합니까?

+1

자산에서 모든 파일이 읽기 전용이기 때문에 런타임시 자산의 파일에 데이터를 추가 할 수 없습니다. – greenapps

+1

Assets 폴더는 응용 프로그램의 읽기 전용 빌드 타임 리소스입니다. 파일이 APK에 지정되면 런타임에 변경할 수 없습니다. –

답변

0

: 덕분에 코드

2 읽기 JSON 파일

String content = getJsonFromAssetFile("T_Difficult.json"); 

3 만들기 최종 JSON으로 방법을 getJsonFromAssetFilewriteFile을 다음

1 추가하십시오 (언급 한 바와 같이)

JSONObject finalJson = new JSONObject(); 

    try { 
     JSONObject jsonObject = new JSONObject(content); 

     JSONArray jsonArray = new JSONArray(); 
     jsonArray.put(jsonObject); 

     finalJson.put("T", jsonArray); 

    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

4. 파일에 최종 JSON 쓰기

writeFile(finalJson.toString().getBytes()); 

의 WriteFile

public static void writeFile(byte[] data, File file) throws IOException { 

    BufferedOutputStream bos = null; 

    try { 
     FileOutputStream fos = new FileOutputStream(file); 
     bos = new BufferedOutputStream(fos); 
     bos.write(data); 
    } 
    finally { 
     if (bos != null) { 
      try { 
       bos.flush(); 
       bos.close(); 
      } 
      catch (Exception e) { 
      } 
     } 
    } 
} 

getJsonFromAssetFile

public static String getJsonFromAssetFile(Context context, String jsonFileName) { 

    String json = null; 
    try { 

     InputStream is = context.getAssets().open(jsonFileName); 

     int size = is.available(); 

     byte[] buffer = new byte[size]; 

     is.read (buffer); 

     is.close(); 

     json = new String(buffer, ServiceConstants.ENCODING); 

    } 
    catch(IOException ex) { 
     ex.printStackTrace(); 
     return null; 
    } 
    return json; 

} 

참고 : getJsonFromAssetFile 방법을 사용하여 JSON 자산 파일을 읽고 내부/외부 저장 장치에 파일을 쓰기에 적절한 경로를 제공하십시오.메소드

+0

답장을 보내 주셔서 감사합니다! 나는 추가했다 :'File file = new File ("C : \\ Users \\ y50-70 \\ Desktop \\ T2 \\ app \\ src \\ main \\ assets \\ T.json"); 그리고 나는 불행하게도'FileOutputStream fos = new FileOutputStream (file);'바로 뒤에 finally 절로 이동한다. 그 이유가 무엇인지 아십니까? BTW 나는 무엇이'ServiceConstants.ENCODING'인지 전혀 모른다. 그게 뭐야? 어떻게 가져올 수 있습니까? – Tomas

+0

@ 토마스 "C : \\ Users \\ y50-70 \\ 바탕 화면 \\ T2 \\ 응용 프로그램 \\ src \\ 메인 \\ 자산 \\ – Pehlaj

+0

경로를 언급하지 마십시오. String content = getJsonFromAssetFile (" T.json "); 경로를 언급 할 필요가 없습니다. 데스크톱 컴퓨터가 아닌 Android 휴대 전화에서 실행됩니다. – Pehlaj