외로운 Nova의 작업실

안드로이드 앱 프로그래밍 - 34(파일에 보관하기) 본문

Programming/Kotlin - Android

안드로이드 앱 프로그래밍 - 34(파일에 보관하기)

Nova_ 2023. 3. 1. 15:34

- 내장 메모리와 외장메모리

안드로이드에서 파이저장소는 내장 메모리와 외장메모리 공간으로 구분됩니다. 외장 메모리 공간은 다시 앱별 저장소와 공용저장소로 나뉩니다. 앱별 저장소에는 다른 앱이 접근할 수 없지만 공용 저장소에는 다른 앱이 접근할 수 있습니다.

 

- 내장 메모리의 파일 이용하기

내장메모리는 앱이 설치되면 시스템에서 자동으로 할당해줍니다. 안드로이드 시스템에서는 앱에서 파일을 이용하지않더라도 앱의 패키지명으로 디렉터리를 만들어줍니다. 이 디렉터리가 앱의 내장 메모리공간입니다. 하지만 내장 메모리는 외장 메모리보다 용량이 작아서 크기가 큰 데이터는 외장 메모리를 이용해야합니다. test.txt파일을 만들고 helloworld를 입력한후 값을 가져와 액티비티에 뿌려주는 앱을 만들어보겠습니다. 아래는 메인액티비티.kt 파일입니다.

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val Binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(Binding.root)

        //create file object
        val file = File(filesDir, "test.txt")

        //write file
        val writeStream: OutputStreamWriter = file.writer()
        writeStream.write("hello world")
        writeStream.flush()

        Binding.fileButton.setOnClickListener(){
            //get file data
            val readStream: BufferedReader = file.reader().buffered()
            readStream.forEachLine {
                Binding.fileData.text = "$it"
            }
        }


    }


}

아래는 메인액티비티.xml파일입니다.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/fileButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="392dp"
        android:text="File"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/fileData"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/fileButton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Comments