Assets폴더에서 파일 읽어오기



java)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.ghj.blog_032;
 
import android.content.res.AssetManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
public class MainActivity extends AppCompatActivity {
 
    //UI
    TextView txtData;
 
    //manager
    AssetManager assetManager;
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        //UI
        txtData = (TextView)findViewById(R.id.txtData);
 
        //manager
        assetManager = getResources().getAssets();
    }
 
    public void mOnAssetData(View v){
        getDataFromAsset();
    }
 
    public void getDataFromAsset(){
        InputStream inputStream = null;
 
        try{
            //asset manager에게서 inputstream 가져오기
            inputStream = assetManager.open("AndroidManifest.txt", AssetManager.ACCESS_BUFFER);
 
            //문자로 읽어들이기
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
 
            //파일읽기
            String strResult = "";
            String line = "";
            while((line=reader.readLine()) != null){
                strResult += line;
            }
 
            //읽은내용 출력
            txtData.setText(strResult);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (inputStream != null) {
                try { inputStream.close(); } catch (IOException e) {}
            }
        }
    }
}
 
cs



xml)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <Button
        android:text="데이터 가져오기"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="mOnAssetData"/>
 
    <TextView
        android:id="@+id/txtData"
        android:textSize="16dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
 
</LinearLayout>
 
cs



결과

버튼을 클릭하면 Assets폴더의 AndroidManifest.txt 파일을 읽어 출력한다

 


+ Recent posts