Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 오버라이딩
- stylesheet
- array
- 구글맵스
- npm
- Hook
- 랜덤넘버
- Java
- Android
- 자바스크립트
- scrollview
- 코틀린
- button
- TextView
- 안드로이드
- nodejs
- React
- fragment
- 스프링부트
- Linux
- GoogleMaps
- 리액트
- RecyclerView
- Javscript
- Kotlin
- 랜덤번호
- JS
- JavaScript
- TypeScript
- SpringBoot
Archives
- Today
- Total
타닥타닥 개발자의 일상
Kotlin 코틀린 문장 입력하면 출력하는 안드로이드 프로그램 만들기 / BufferedReader / OutputStreamWriter 이용 / 파일 입출력 본문
코딩 기록/Kotlin
Kotlin 코틀린 문장 입력하면 출력하는 안드로이드 프로그램 만들기 / BufferedReader / OutputStreamWriter 이용 / 파일 입출력
NomadHaven 2022. 2. 10. 21:22
activity_main
<?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="483dp"
android:layout_height="55dp"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/editText"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintHorizontal_bias="0.504"
app:layout_constraintVertical_bias="0.238"/>
<Button
android:text="쓰기"
android:layout_width="148dp"
android:layout_height="81dp" android:id="@+id/write"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintVertical_bias="0.361"
app:layout_constraintHorizontal_bias="0.774"/>
<Button
android:text="읽기"
android:layout_width="148dp"
android:layout_height="81dp"
android:id="@+id/read"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintVertical_bias="0.361"
app:layout_constraintHorizontal_bias="0.216"/>
<Button
android:text="clear"
android:layout_width="396dp"
android:layout_height="78dp"
android:id="@+id/clear"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintHorizontal_bias="0.48"
app:layout_constraintVertical_bias="0.587"/>
</androidx.constraintlayout.widget.ConstraintLayout>
EditText를 통하여 문자를 입력받을 공간을 만든다.
읽기 버튼을 누르면 이전에 저장된 값이 불려오고 문자를 입력한뒤 쓰기를 누르면 데이터가 저장된다.
CLEAR 버튼을 누르면 입력창에 입력된 값, 혹은 불려온 값이 사라진다.
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
//저장내용을 읽어들이는 reader라는 변수를 null로 초기화
val `in`:InputStream? = openFileInput(NOTES)
//NOTES라는 파일에 저장하된 `in`이라는 변수
try {
if (`in` != null) { //저장내용이 null이 아닐때
reader = BufferedReader(InputStreamReader(`in`))
//reader라는 변수(BufferedReader)통해 저장내용을 읽어들인다.
var str: String? = null
//StringBuffer는 ()안에 값을 입력받고 후에 수정도 가능한 메서드다
val buf = StringBuffer()
while (reader.readLine().also { str = it } != null) {
//readLine하고 전달받은 it은 str로 초기화 일때, 그 값은 null이 아니다
//즉 전달받은 값이 있으므로 저장된 값이 있다는 말
println("$str")
//StringBuffer의 빈 값에 입력받은 str을 넣는다.
buf.append("""$str""") //실제 읽는 부분
}
edit.setText(buf.toString()) // 불러온 값을 buf를 통해 edit창에 불러온다.
}
} catch (e:FileNotFoundException){
} catch(e:Exception){
println(e.message)
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{ //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("")
//clear 버튼을 누를시 입력창을 지운다.
}
}
}
입력한 문자가 저장된 위치 확인하는 법
보기 > 도구창 > Device FIle Expolore
본인이 만든 앱의 이름을 클릭 > files > notes에 입력한 문장이 저장된다.
난 테스트할때 짜장면 짬뽕 능력 향상 난 이라는 문장을 입력했다.
![](https://t1.daumcdn.net/keditor/emoticon/friends1/large/016.gif)
자동완성으로 입력해서 저렇다.
실행화면
'코딩 기록 > Kotlin' 카테고리의 다른 글
kotlin 코틀린 클래스에서 Parcelable 상속 하기 / Parcelable 기능으로 첫번째 화면에서 받은 데이터 두번째 화면으로 전달하는 안드로이드 화면 만들기 (0) | 2022.02.10 |
---|---|
Kotlin 코틀린 JSON 이용하여 안드로이드 화면에 전송한 자료 출력하기 (0) | 2022.02.10 |
Kotlin 코틀린 random 넘버와 spinner 이용한 안드로이드 야구 게임 만들기 (0) | 2022.02.10 |
Kotlin 안드로이드 화면에 recyclerView 사용해서 프로필 목록 만들고 프로필 클릭시 상세 화면 전환하기 (0) | 2022.02.09 |
kotlin BooleanArray, Math.random 이용하여 중복되지 않는 랜덤 번호 골라주는 함수 만들기 (0) | 2022.02.08 |
Comments