YSHUSH

File 본문

Coding/Android(kotlin)

File

코딩; 2022. 2. 10. 16:33

 

단어나 문장을 쓰고 쓰기 버튼을 누르면 file에 저장이 되고
읽기 버튼을 누르면 썼던 단어나 문장이 나오게 해보자

 

 

1. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    <EditText
            android:layout_width="487dp"
            android:layout_height="58dp"
            android:inputType="textPersonName"
            android:ems="10"
            android:id="@+id/editText"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintHorizontal_bias="0.504"
            app:layout_constraintVertical_bias="0.221"/>
    <Button
            android:text="읽기"
            android:layout_width="220dp"
            android:layout_height="63dp"
            android:id="@+id/read"
            app:layout_constraintTop_toBottomOf="@+id/editText"
            android:layout_marginTop="36dp"
            app:layout_constraintStart_toStartOf="parent"
            android:layout_marginStart="56dp"/>
    <Button
            android:text="쓰기"
            android:layout_width="220dp"
            android:layout_height="63dp"
            android:id="@+id/write"
            app:layout_constraintTop_toTopOf="@+id/read"
            app:layout_constraintStart_toEndOf="@+id/read"
            android:layout_marginStart="44dp"/>
    <Button
            android:text="clear"
            android:layout_width="487dp"
            android:layout_height="63dp"
            android:id="@+id/clear"
            app:layout_constraintTop_toBottomOf="@+id/read"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintHorizontal_bias="0.504"
            app:layout_constraintVertical_bias="0.064"/>
</androidx.constraintlayout.widget.ConstraintLayout>

 

 

2. MainActivity.kt

package com.example.sample31

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.ContactsContract.Intents.Insert.NOTES
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import java.io.*
import java.lang.Exception

class MainActivity : AppCompatActivity(), View.OnClickListener {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val read = findViewById<Button>(R.id.read)
        val write = findViewById<Button>(R.id.write)
        val clear = findViewById<Button>(R.id.clear)

        read.setOnClickListener(this)
        write.setOnClickListener(this)
        clear.setOnClickListener(this)

    }

    override fun onClick(view: View?) {
        val edit = findViewById<EditText>(R.id.editText)

        if(view?.id == R.id.read){

            var reader: BufferedReader? = null

            try {
                val `in`: InputStream? = openFileInput(NOTES)

                if (`in` != null) {
                    reader = BufferedReader(InputStreamReader(`in`))
                    var str: String? = null
                    val buf = StringBuffer()

                    while (reader.readLine().also { str = it } != null) {
                        println("$str")
                        buf.append("""$str""")
                    }
                    edit.setText(buf.toString())
                }
            }catch (e:FileNotFoundException){

            }catch (e:Exception){
                Toast.makeText(this, "예외: $e", Toast.LENGTH_SHORT).show()
            } finally {
                if (reader != null) try {
                    reader?.close()
                }catch (e:Exception){}
            }
        }
        else if(view?.id == R.id.write){
            var out:OutputStreamWriter? = null

            try{
                // NOTES가 파일명을 알아서 정해줌, MODE_PRIVATE = 덮어쓰기, MODE_APPEND = 이어쓰기
                out = OutputStreamWriter(openFileOutput(NOTES, MODE_PRIVATE))
                out.write(edit.text.toString())

                Toast.makeText(this, "데이터저장", Toast.LENGTH_SHORT).show()

            }catch (e:Exception){
                e.printStackTrace()
            }finally {
                if(out != null) try {
                    out.close()
                }catch(e:IOException){}
            }
        }
        else if(view?.id == R.id.clear){
            edit.setText("")
        }
    }
}

 

보기 - 도구창 - Device File Explorer

보기 - 도구창 - Device File Explorer에 들어가고

 

data - data

data - data폴더에 들어가면 안드로이드에서 설치한 폴더가 나오는데 해당 패키지명 - files - notes파일을 보면 입력한 텍스트를 볼 수 있다.

 

개인용 앱의 경우 file에 아이디나 비밀번호를 저장하는 경우가 많다!

'Coding > Android(kotlin)' 카테고리의 다른 글

화면 전환(Preference)  (0) 2022.02.10
JSON  (0) 2022.02.10
Counter(숫자 세기 미니 프로그램)  (0) 2022.02.08
Rating bar  (0) 2022.02.08
Seek bar  (0) 2022.02.08