Android 외부 저장소 – 파일 읽기, 쓰기, 저장하기

안드로이드 외부 저장소는 데이터를 작성하고 저장하며 구성 파일 등을 읽을 수 있습니다. 이 기사는 Android 내부 저장소 튜토리얼의 연속입니다. 시리즈 안드로이드에서의 구조화된 데이터 저장에 대한 튜토리얼입니다.

Android 외부 저장소

SD 카드와 같은 외부 저장소는 응용 프로그램 데이터를 저장할 수도 있습니다. 여기에 저장하는 파일에 대해 시스템에서 시행하는 보안이 없습니다. 일반적으로 두 가지 유형의 외부 저장소가 있습니다:

  • 기본 외부 저장소: 내장된 공유 저장소로 “USB 케이블을 연결하고 호스트 컴퓨터에서 드라이브로 마운트할 수 있는” 것입니다. 예: Nexus 5 32GB라고 말할 때.
  • 보조 외부 저장소: 탈부착식 저장소. 예: SD 카드

모든 응용 프로그램은 외부 저장소에 저장된 파일을 읽고 쓸 수 있으며 사용자는 이를 제거할 수 있습니다. SD 카드를 사용할 수 있고 쓸 수 있는지 확인해야 합니다. 외부 저장소가 사용 가능한지 확인한 후에만 쓸 수 있습니다. 그렇지 않으면 저장 버튼이 비활성화됩니다.

Android 외부 저장소 예제 프로젝트 구조

먼저, 애플리케이션이 사용자 SD 카드에 데이터를 읽고 쓸 수 있는 권한이 있는지 확인해야 합니다. 따라서 AndroidManifest.xml을 열고 다음 권한을 추가합니다:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

또한, 외부 저장소는 사용자가 USB 저장 장치로 마운트했을 수 있습니다. 따라서 외부 저장소가 사용 가능하고 읽기 전용이 아닌지 확인해야 합니다.

if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {  
   saveButton.setEnabled(false);
  }  

private static boolean isExternalStorageReadOnly() {  
  String extStorageState = Environment.getExternalStorageState();  
  if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {  
   return true;  
  }  
  return false;  
 }  
 
 private static boolean isExternalStorageAvailable() {  
  String extStorageState = Environment.getExternalStorageState();  
  if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {  
   return true;  
  }  
  return false;  
 }  

getExternalStorageState()는 현재 외부 저장소를 사용할 수 있는지 여부를 결정하는 Environment의 정적 메서드입니다. 조건이 false인 경우 저장 버튼이 비활성화된 것을 볼 수 있습니다.

Android 외부 저장소 예제 코드

activity_main.xml 레이아웃은 다음과 같이 정의됩니다:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:orientation="vertical">

    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Reading and Writing to External Storage"
        android:textSize="24sp"/>

    <EditText android:id="@+id/myInputText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" android:lines="5"
        android:minLines="3" android:gravity="top|left"
        android:inputType="textMultiLine">

        <requestFocus />
    </EditText>

    <LinearLayout
    android:layout_width="match_parent" android:layout_height="wrap_content"
    android:orientation="horizontal"
        android:weightSum="1.0"
        android:layout_marginTop="20dp">

    <Button android:id="@+id/saveExternalStorage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="SAVE"
        android:layout_weight="0.5"/>

    <Button android:id="@+id/getExternalStorage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:text="READ" />

    </LinearLayout>

    <TextView android:id="@+id/response"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:padding="5dp"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>

여기에서는 외부 저장소에서 저장하고 읽기 버튼 이외에도 이전 튜토리얼과 달리 텍스트뷰에 외부 저장소에 저장/읽기 응답을 표시합니다. 아래는 MainActivity.java 클래스입니다:

package com.journaldev.externalstorage;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import android.os.Bundle;
import android.app.Activity;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class MainActivity extends Activity {
    EditText inputText;
    TextView response;
    Button saveButton,readButton;

    private String filename = "SampleFile.txt";
    private String filepath = "MyFileStorage";
    File myExternalFile;
    String myData = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        inputText = (EditText) findViewById(R.id.myInputText);
        response = (TextView) findViewById(R.id.response);


         saveButton =
                (Button) findViewById(R.id.saveExternalStorage);
        saveButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    FileOutputStream fos = new FileOutputStream(myExternalFile);
                    fos.write(inputText.getText().toString().getBytes());
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                inputText.setText("");
                response.setText("SampleFile.txt saved to External Storage...");
            }
        });

        readButton = (Button) findViewById(R.id.getExternalStorage);
        readButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    FileInputStream fis = new FileInputStream(myExternalFile);
                    DataInputStream in = new DataInputStream(fis);
                    BufferedReader br =
                            new BufferedReader(new InputStreamReader(in));
                    String strLine;
                    while ((strLine = br.readLine()) != null) {
                        myData = myData + strLine;
                    }
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                inputText.setText(myData);
                response.setText("SampleFile.txt data retrieved from Internal Storage...");
            }
        });

        if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
            saveButton.setEnabled(false);
        }
        else {
            myExternalFile = new File(getExternalFilesDir(filepath), filename);
        }


    }
    private static boolean isExternalStorageReadOnly() {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
            return true;
        }
        return false;
    }

    private static boolean isExternalStorageAvailable() {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
            return true;
        }
        return false;
    }


}
  1. Environment.getExternalStorageState(): “mnt/sdcard”와 같은 내부 SD 마운트 포인트 경로를 반환합니다.
  2. getExternalFilesDir(): SD 카드의 Android/data/data/application_package/ 내부에있는 파일 폴더의 경로를 반환합니다. 이 폴더에는 웹에서 다운로드 된 이미지 또는 캐시 파일과 같은 앱에 필요한 파일을 저장하는 데 사용됩니다. 앱이 제거되면이 폴더에 저장된 데이터가 모두 삭제됩니다.

외부 저장소를 사용할 수 없는 경우 이전 튜토리얼에서 논의된 조건문을 사용하여 저장 버튼을 비활성화합니다. 아래는 파일에 데이터를 쓰고 읽는 안드로이드 에뮬레이터에서 애플리케이션을 실행하는 모습입니다. 참고: Android 에뮬레이터가 SD 카드를 보유하고 있는지 확인하십시오. 아래의 AVD 이미지 대화 상자에서 확인할 수 있습니다. 도구로 이동->Android->Android 가상 장치, 구성 편집->고급 설정 표시. 이로써 이 튜토리얼을 마칩니다. 다음 튜토리얼에서는 SharedPreferences를 사용하여 저장소에 대해 논의할 것입니다. 아래 링크에서 최종 Android 외부 저장소 프로젝트를 다운로드할 수 있습니다.

Android 외부 저장소 예제 프로젝트 다운로드

Source:
https://www.digitalocean.com/community/tutorials/android-external-storage-read-write-save-file