안드로이드
안드로이드(Android) 원본 리소스 raw
초코비니
2015. 9. 16. 00:35
txt 파일, 음악파일, 동영상 파일 등 기타 원본 리소스들은 /res/raw 폴더 밑에서 관리한다.
해당 원본 파일들을 raw 밑에 넣어두기만 하면 된다.
raw 폴더를 새로 만들고 원본파일을 넣자.
1. res(리소스)에 raw 폴더 생성 후 원본파일 저장
/res/ 밑에 raw 폴더를 만들고 mymusic.mp3 파일과 mytext.txt 파일을 넣어놨다.
mytext.txt 파일에는 "Hello~ Android!" 가 저장되어 있다.
2. txt 파일의 내용을 보여줄 <TextView> 작성
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:id="@+id/textView01" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </RelativeLayout> |
- ID : textView01 로 <TextView> 를 등록했다.
3. Activity.java 에서 mytext.txt, mymusic.mp3 읽어오기
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try{ // getResources().openRawResource()로 raw 폴더의 원본 파일을 가져온다. // txt 파일을 InpuStream에 넣는다. (open 한다) InputStream in = getResources().openRawResource(R.raw.mytext); if(in != null){ InputStreamReader stream = new InputStreamReader(in, "utf-8"); BufferedReader buffer = new BufferedReader(stream); String read; StringBuilder sb = new StringBuilder(""); while((read=buffer.readLine())!=null){ sb.append(read); } in.close(); // id : textView01 TextView를 불러와서 //메모장에서 읽어온 문자열을 등록한다. TextView textView =(TextView)findViewById(R.id.textView01); textView.setText(sb.toString()); } }catch(Exception e){ e.printStackTrace(); } // music.mp3 파일 역시 getResources().openRawResource()로 //가져올 수 있다. // 여기서는 MediaPlayer로도 음악 파일을 가져오고 // start()로 실행할 수 있다. MediaPlayer player = MediaPlayer.create(this, R.raw.mymusic); player.start(); } } |
- getResources().openRawResource() 를 사용하여 raw 폴더의 원본파일을 가져온다.
- mytext.txt 파일을 읽어 <TextView>에 등록하여 출력한다.
- 음악파일인 mymusic.mp3 역시 getResources().openRawResource() 로 불러올 수 있지만 음악 파일을 지원하는 MediaPlayer로 호출한 후 start() 메소드로 음악을 실행시킨다.
프로그램 실행
- mytext.txt 에 있는 Hello~ Android! 를 읽어와 출력한다.
- mymusic.mp3 가 실행되어 음악이 나온다.
출처 : http://hyeonstorage.tistory.com/159