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

안드로이드 내부 저장소에서 TXT 파일 생성 및 읽기 방법 완벽 가이드

이 튜토리얼에서는 안드로이드 앱의 내부 저장소(Internal Storage)에 TXT 파일을 생성하고, 저장된 파일을 다시 읽어 화면에 출력하는 방법을 단계별로 알아봅니다.

1단계: 새 프로젝트 생성

Android Studio를 실행한 후 File → New Project 메뉴로 이동하여 새 프로젝트를 생성합니다. 프로젝트 생성에 필요한 모든 세부 정보를 입력하고 진행하세요.

2단계: 레이아웃 XML 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout 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"
    tools:context = ".MainActivity"
    android:orientation = "vertical">
    <EditText
        android:id = "@+id/enterText"
        android:hint = "Please enter text here"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content" />
    <Button
        android:id = "@+id/save"
        android:text = "Save"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content" />
    <TextView
        android:id = "@+id/output"
        android:layout_width = "wrap_content"
        android:textSize = "25sp"
        android:layout_height = "wrap_content" />
</LinearLayout>

위 레이아웃은 크게 세 가지 요소로 구성되어 있습니다.

  • EditText: 사용자가 저장할 텍스트를 입력하는 입력창
  • Button: 클릭 시 텍스트를 파일로 저장하는 버튼
  • TextView: 파일에서 읽어온 내용을 화면에 표시하는 영역

사용자가 버튼을 클릭하면 EditText에 입력된 데이터를 가져와 내부 저장소의 /data/data/<your.package.name>/files/text/sample.txt 경로에 저장합니다. 이후 sample.txt 파일의 내용을 읽어 TextView에 출력하게 됩니다.

3단계: MainActivity.java 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다.

package com.example.andy.myapplication;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {
    Button save;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final TextView output = findViewById(R.id.output);
        final EditText enterText = findViewById(R.id.enterText);
        save = findViewById(R.id.save);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!enterText.getText().toString().isEmpty()) {
                    File file = new File(MainActivity.this.getFilesDir(), "text");
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    try {
                        File gpxfile = new File(file, "sample");
                        FileWriter writer = new FileWriter(gpxfile);
                        writer.append(enterText.getText().toString());
                        writer.flush();
                        writer.close();
                        output.setText(readFile());
                        Toast.makeText(MainActivity.this, "Saved your text", Toast.LENGTH_LONG).show();
                    } catch (Exception e) { }
                }
            }
        });
    }
    private String readFile() {
        File fileEvents = new File(MainActivity.this.getFilesDir()+"/text/sample");
        StringBuilder text = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(fileEvents));
            String line;
            while ((line = br.readLine()) ! = null) {
                text.append(line);
                text.append('\n');
            }
            br.close();
        } catch (IOException e) { }
        String result = text.toString();
        return result;
    }
}

코드의 핵심 동작 흐름은 다음과 같습니다.

  1. 입력값 검증: EditText가 비어 있지 않은지 먼저 확인합니다.
  2. 디렉터리 생성: getFilesDir()로 얻은 내부 저장소 경로 아래에 'text' 폴더가 없으면 새로 만듭니다.
  3. 파일 쓰기: FileWriter를 사용해 입력된 텍스트를 sample 파일에 기록한 후 flush()와 close()로 스트림을 정리합니다.
  4. 파일 읽기: readFile() 메서드에서 BufferedReader의 readLine()으로 파일을 한 줄씩 읽어 StringBuilder에 누적한 뒤 문자열로 반환합니다.
  5. 결과 출력: 읽어온 내용을 TextView에 설정하고, 저장 성공 시 Toast 메시지를 표시합니다.

4단계: 매니페스트 설정

manifest.xml 파일에 아래 코드를 추가합니다.

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "https://schemas.android.com/apk/res/android"
    package = "com.example.andy.myapplication">
    <uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name = "android.permission.READ_EXTERNAL_STORAGE"/>
    <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>

참고: 내부 저장소(getFilesDir())는 해당 앱 전용 영역이므로 별도의 권한 없이 접근할 수 있습니다. 위 예제의 외부 저장소 권한은 참고용으로 포함된 것이며, 내부 저장소만 사용한다면 생략해도 무방합니다.

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하세요. 실행 옵션에서 자신의 모바일 기기를 선택하면, 기본 화면이 표시됩니다.

안드로이드 내부 저장소에서 TXT 파일 생성 및 읽기 방법 완벽 가이드

위 화면에서 텍스트를 입력하고 Save 버튼을 클릭하면 아래와 같이 결과가 나타납니다.

안드로이드 내부 저장소에서 TXT 파일 생성 및 읽기 방법 완벽 가이드

저장이 정상적으로 완료되었는지 확인하려면 /data/data/<your.package.name>/files/text/sample.txt 경로의 파일을 열어 아래와 같이 내용이 기록되어 있는지 확인하면 됩니다.

안드로이드 내부 저장소에서 TXT 파일 생성 및 읽기 방법 완벽 가이드