웹사이트 검색

Android 내부 저장소 예제 자습서


오늘은 안드로이드 내부 저장소에 대해 알아보겠습니다. Android는 데이터를 저장하는 몇 가지 구조화된 방법을 제공합니다. 여기에는 다음이 포함됩니다.

  • 공유 기본 설정
  • 내부 저장소
  • 외부 저장소
  • SQLite 저장소
  • 네트워크 연결을 통한 저장(클라우드)

이 튜토리얼에서는 Android 내부 저장소를 사용하여 데이터를 파일로 저장하고 읽는 방법을 살펴보겠습니다.

Android 내부 저장소

Android 내부 저장소는 기기 메모리에 개인 데이터를 저장하는 저장소입니다. 기본적으로 내부 저장소에 파일을 저장하고 로드하는 것은 애플리케이션 전용이며 다른 애플리케이션은 이러한 파일에 액세스할 수 없습니다. 사용자가 애플리케이션을 제거하면 애플리케이션과 관련된 내부 저장 파일도 제거됩니다. 그러나 일부 사용자는 Android 휴대폰을 루팅하여 수퍼유저 액세스 권한을 얻습니다. 이 사용자는 원하는 파일을 읽고 쓸 수 있습니다.

Android 내부 저장소에서 텍스트 파일 읽기 및 쓰기

Android는 Java I/O 클래스의 openFileInputopenFileOutput을 제공하여 로컬 파일에서 스트림 읽기 및 쓰기를 수정합니다.

  • openFileOutput(): This method is used to create and save a file. Its syntax is given below:

    FileOutputStream fOut = openFileOutput("file name",Context.MODE_PRIVATE);
    

    The method openFileOutput() returns an instance of FileOutputStream. After that we can call write method to write data on the file. Its syntax is given below:

    String str = "test data";
    fOut.write(str.getBytes());
    fOut.close();
    
  • openFileInput(): This method is used to open a file and read it. It returns an instance of FileInputStream. Its syntax is given below:

    FileInputStream fin = openFileInput(file);
    

    After that, we call read method to read one character at a time from the file and then print it. Its syntax is given below:

    int c;
    String temp="";
    while( (c = fin.read()) != -1){
       temp = temp + Character.toString((char)c);
    }
    
    fin.close();
    

    In the above code, string temp contains all the data of the file.

  • Note that these methods do not accept file paths (e.g. path/to/file.txt), they just take simple file names.

Android 내부 저장소 프로젝트 구조

Android 내부 저장소 예제 코드

xml 레이아웃에는 파일에 데이터를 쓰기 위한 EditText와 쓰기 버튼 및 읽기 버튼이 포함되어 있습니다. onClick 메서드는 아래와 같이 xml 파일에서만 정의됩니다. activity_main.xml

<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"
    >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:padding="5dp"
        android:text="Android Read and Write Text from/to a File"
        android:textStyle="bold"
        android:textSize="28sp" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="22dp"
        android:minLines="5"
        android:layout_margin="5dp">

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Write Text into File"
        android:onClick="WriteBtn"
        android:layout_alignTop="@+id/button2"
        android:layout_alignRight="@+id/editText1"
        android:layout_alignEnd="@+id/editText1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Read Text From file"
        android:onClick="ReadBtn"
        android:layout_centerVertical="true"
        android:layout_alignLeft="@+id/editText1"
        android:layout_alignStart="@+id/editText1" />

</RelativeLayout>

MainActivity에는 위에서 설명한 대로 파일 읽기 및 쓰기 구현이 포함되어 있습니다.

package com.journaldev.internalstorage;


import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class MainActivity extends Activity {

    EditText textmsg;
    static final int READ_BLOCK_SIZE = 100;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textmsg=(EditText)findViewById(R.id.editText1);
    }

    // write text to file
    public void WriteBtn(View v) {
        // add-write text into file
        try {
            FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
            OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
            outputWriter.write(textmsg.getText().toString());
            outputWriter.close();

            //display file saved message
            Toast.makeText(getBaseContext(), "File saved successfully!",
                    Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Read text from file
    public void ReadBtn(View v) {
        //reading text from file
        try {
            FileInputStream fileIn=openFileInput("mytextfile.txt");
            InputStreamReader InputRead= new InputStreamReader(fileIn);

            char[] inputBuffer= new char[READ_BLOCK_SIZE];
            String s="";
            int charRead;

            while ((charRead=InputRead.read(inputBuffer))>0) {
                // char to string conversion
                String readstring=String.copyValueOf(inputBuffer,0,charRead);
                s +=readstring;
            }
            InputRead.close();
            textmsg.setText(s);
            

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

파일은 어디에 있습니까?

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