Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드 앱에서 간단한 텍스트 파일을 읽는 방법 – 단계별 완벽 가이드


이 예제에서는 안드로이드 앱에서 간단한 텍스트 파일을 읽어 화면에 표시하는 방법을 알아봅니다. res/raw 폴더에 저장된 텍스트 파일을 BufferedReader로 한 줄씩 읽어 TextView에 출력하는 가장 기본적인 패턴을 단계별로 살펴보겠습니다.

1단계 – 새 프로젝트 생성 및 raw 리소스 준비

안드로이드 스튜디오에서 File ⇒ New Project를 선택해 새 프로젝트를 만들고, 필요한 정보를 모두 입력합니다.

그다음 새로운 Android Resource 디렉터리(raw)를 생성하고, 읽고자 하는 텍스트 파일(예: sample.txt)을 res/raw 폴더 안에 추가합니다.

2단계 – activity_main.xml 레이아웃 작성

res/layout/activity_main.xml에 다음 코드를 추가합니다. 텍스트 파일을 읽어올 버튼과 결과를 표시할 TextView 두 개로 구성된 간단한 레이아웃입니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp"
    tools:context=".MainActivity">
    <Button
       android:id="@+id/button"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_centerHorizontal="true"
       android:layout_marginTop="70dp"
       android:onClick="ReadTextFile"
       android:text="Read Text File" />
    <TextView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_marginTop="20dp"
       android:text="Read text File in Android"
       android:textAlignment="center"
       android:textSize="18sp"
       android:textStyle="bold" />
    <TextView
       android:id="@+id/textView"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/button"
       android:layout_marginTop="10dp"
       android:textSize="20sp"
       android:textStyle="bold" />
</RelativeLayout>

3단계 – MainActivity.java 코드 작성

src/MainActivity.java에 다음 코드를 추가합니다. openRawResource() 메서드로 파일 스트림을 열고, BufferedReader를 통해 한 줄씩 읽어 StringBuilder에 누적한 뒤 TextView와 Toast로 화면에 표시합니다.

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
    }
    public void ReadTextFile(View view) throws IOException {
        String string = "";
        StringBuilder stringBuilder = new StringBuilder();
        InputStream is = this.getResources().openRawResource(R.raw.sample);
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        while (true) {
            try {
                if ((string = reader.readLine()) == null) break;
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            stringBuilder.append(string).append("\n");
            textView.setText(stringBuilder);
        }
        is.close();
        Toast.makeText(getBaseContext(), stringBuilder.toString(),
        Toast.LENGTH_LONG).show();
    }
}

4단계 – AndroidManifest.xml 설정

androidManifest.xml에 다음 코드를 추가합니다. raw 리소스는 앱 내부에 포함된 파일이므로 인터넷이나 저장소 접근과 같은 별도의 권한(permission) 선언이 필요하지 않습니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. 안드로이드 스튜디오에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하세요. 실행 옵션에서 모바일 기기를 선택하면, 기기에 기본 화면이 표시되고 버튼을 누르면 텍스트 파일의 내용이 그대로 출력됩니다.

안드로이드 앱에서 간단한 텍스트 파일을 읽는 방법 – 단계별 완벽 가이드