본문 바로가기
C++ 200제/코딩 IT 정보

안드로이드 txt 읽기 예제, InputStream 사용 (한글 깨짐 해결)

by vicddory 2017. 11. 26.

안드로이드 txt 읽기 예제, InputStream 사용 (한글 깨짐 해결)


아래 안드로이드 TXT 예제(InputStream 사용)에서는 임의 XML 파일 이외에도 미가공 파일을 사용할 수 있다. res / 밑에 raw폴더와 asset 폴더에 오디오, 비디오, text 파일을 저장하고 해당 파일을 읽을 수 있다.


InputStream을 이용해 raw 리소스 읽어 들이는 형식과 asset에서 읽어 들이는 형식으로 몇 개 짜보았다. main Keword는 InputStream으로 읽어서, 1byte씩 조각내서 쓴다.


한글 때문에 뻑나면, StreamReader로 해당 charset에 맞춰서 읽는다. String이나 StringBuffer나 StringBuilder 모두 사용해봤는데, 그다지 차이는 없는 듯.


안드로이드 InputStream 예제[안드로이드 txt 읽기 예제, InputStream 사용 (한글 깨짐 해결)


[안드로이드 예제 InputStream] 1. asset road resource


1
2
3
4
5
6
7
8
9
10
11
12
private String getStringAssetFile(Activity activity) throws Exception {
    AssetManager as = activity.getAssets();
    InputStream is = as.open("text1.txt");
 
    // InputStreamReader isr = new
    // InputStreamReader(as.open("text1.txt"),"EUC-KR");
 
    String text = convertStreamToString(is);
    is.close();
 
    return text;
}
cs


[안드로이드 예제 InputStream] 2. inputStream -> String


1
2
3
4
5
6
7
8
9
10
private String convertStreamToString(InputStream is) throws IOException {
    ByteArrayOutputStream bs = new ByteArrayOutputStream();
     int i = is.read();
 
    while (i != -1) {
        bs.write(i);
        i = is.read();
    }
    return bs.toString();
}
cs


[안드로이드 예제 InputStream] 3. raw road resource -> String-> wirte String Builder


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private String getStringFromRawFile(Activity activity) throws IOException {
 
    Resources r = activity.getResources();
    InputStream is = r.openRawResource(R.raw.text2);
     InputStreamReader r2 = new InputStreamReader(is);
    StringBuilder str = new StringBuilder();
 
    ByteArrayOutputStream bs = new ByteArrayOutputStream();
 
    while (true) {
        int i = r2.read();
 
        if (i == -1)
            break;
        else {
            char c = (char) i;
            str.append(c);
            bs.write(c);
        }
    }
    // StringBuilder sb = sb.append(c);
    // Str    ing myText = is.close();
    return bs.toString();
}
cs


안드로이드 txt 읽기 예제, InputStream 사용 (한글 깨짐 해결)

댓글