2014년 8월 6일 수요일

[Android] assets 파일 읽어오기


어플을 만들때, 일일이 String으로 글을 적어 넣기도 하지만, 약관이나 정책등 이미 정의된 문서가 있을경우 이자체를 파일로 

바로 읽어 드려도 될것이다. 다시 일일이 치려면,, 노가다일 뿐이니..

간단하게 Asset에서 File을 읽어 드리는 방법에대해 소개 하고자 한다. 


이에 대해 안드로이드에서 읽어 오려면~ 코드를 살펴 보자.
package com.ememomo;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ReadTextFromAsset extends Activity {
 private String assetTxt;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  
  setContentView(R.layout.main);
  TextView text = (TextView)findViewById(R.id.text);
  
  try {
   assetTxt = readText("pushpush.txt");
  } catch (Exception e) {
   e.printStackTrace();
  }
  
  text.setText(assetTxt);
 }
 private String readText(String file) throws IOException {
  InputStream is = getAssets().open(file);
  int size = is.available();
  byte[] buffer = new byte[size];
  is.read(buffer);
  is.close();
  String text = new String(buffer);
  return text;
 }
}


간단하게 readText() 함수내에 파일 이름을 지정해 주면 된다.~ 

댓글 없음:

댓글 쓰기