반응형

# 안드로이드 저장공간 

view - tool window - device file explorer

 

내부 저장공간

앱을 설치할 때 앱만을 위한 전용공간이 할당됨

해당 앱에서만 접근 가능

앱을 삭제하면 해당 공간도 삭제됨 

/data/data/패키지 이름

 

# 내부 저장공간 데이터 쓰기/읽기

FileInputStream, FileOutputStream 클래스를 이용해서

내부 저장소에 데이터를 저장하거나 읽어올 수 있음

 

1. MainPractice생성 

2. layout 버튼 내부 저장공간 데이터 쓰기/읽기 2개 생성

3. MainPractice내부에 FileInputStream / FileOutputStream을 이용해 파일 생성 /읽기

 

 

 

package imlsw96.hellofiles

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.View
import android.widget.Toast
import java.io.FileInputStream
import java.io.FileOutputStream

class MainPractice : AppCompatActivity() {
    var fname = "Hello.txt"     // 생성할 파일 이름을 담을 변수
    var TAG = "MainPractice" // 로그확인을 위해 현재 액티비티 이름을 담는 변수 생성
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main_practice)
    }
    // 내부 저장소 파일 쓰기 메서드
    fun internalFileWrite2 (v: View) {
        // 앱전용 쓰기 경로에 쓰기모드를 연다.
        var ofs : FileOutputStream = openFileOutput(fname, Context.MODE_PRIVATE)

        var contents = "파일에 쓸 내용을 여기다 적는다. 가나다라마바사아자차카타파하"

        ofs.write(contents.toByteArray())
        ofs.close()

        Toast.makeText(applicationContext,"파일 쓰기 완료 ! ",Toast.LENGTH_SHORT).show()

        Log.d(TAG,"파일저장 완료!")
    }

    // 내부 저장소 파일 불러오기 메서드
    fun internalFileRead2(v:View) {
        var ifs : FileInputStream = openFileInput(fname) // 파일을 열기

        var buffer = ByteArray(30) // 파일의 데이터를 30바이트를 가져와 buffer 변수에 담기

        ifs.read(buffer)
        ifs.close()

        var contents = buffer.toString(Charsets.UTF_8) // 가져온 파일내용을 UTF-8로 변환
        Toast.makeText(applicationContext, "파일내용: ${contents}", Toast.LENGTH_SHORT).show()

        Log.d(TAG,"내부저장소에서 읽은 내용은 ${contents}")
    }
}

 

 

반응형

'JAVA & APP :국비지원 학원 복습 > AndroidStudio' 카테고리의 다른 글

실습)동물사진 보기 앱  (0) 2021.02.25
02 안드로이드 : widget  (0) 2021.02.25
01 HelloAndroid  (0) 2021.02.24

+ Recent posts