1.  파일 처리의 기본

안드로이드에서 파일을 읽고 쓰는 방법에는 Java에서 제공하는 파일 관련 클래스를 사용하는 방법과 안드로이드에서 제공하는 파일 관련 클래스를 사용하는 방법이 있음. 아무 곳에서나 파일을 읽고 쓸 수는 없고 제한된 폴더나 SD 카드 등에서만 가능.


1)  내장 메모리 파일 처리

🐰  앱을 종료했다가 다음에 다시 실행할 때 사용하던 곳 부터 이어서 작업하고 싶은 경우,내장 메모리에 파일을 저장하고 읽어오는 방식을 활용
🐰  내장 메모리의 저장 위치는 /data/data/패키지명/files 폴더
      📍 일반적으로 앱마다 다른 패키지명을 사용하므로 앱별로 고유의 저장 공간이 있다고 생각하면 됨

🐰  파일을 읽기 위해 먼저 안드로이드 Context 클래스의 openFileInput() 메서드를 사용 ▶️ FileInputStream을 반환
🐰  파일을 쓰기 위해 openFileOutput() 메서드를 사용 ▶️ FileOutputStream을 반환
🐰  Java에서 제공하는 파일을 읽거나 쓰는 java.io.FileInputStream 클래스와 java.io.FileOuptputStream 클래스의 read(), write() 메서드를 사용하여 파일을 처리

 

내장 메모리에서 파일을 읽거나 쓰는 일반적인 절차
  • openFileInput() / openFileOutput() 으로 파일 열기 : FileInputStream / FileOutputStream 반환
  • read() / write()로 파일 읽기 / 쓰기
  • close()로 파일 닫기
xml 코드
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btnWrite"
        android:text="내장 메모리에 파일 쓰기" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btnRead"
        android:text="내장 메모리에 파일 읽기" />

</LinearLayout>

 

kotlin 코드
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        val btnWrite = findViewById<Button>(R.id.btnWrite)
        val btnRead = findViewById<Button>(R.id.btnRead)

        btnWrite.setOnClickListener {
            val outputStream = openFileOutput("file.txt", Context.MODE_PRIVATE)
            val string = "파일 처리 테스트"
            outputStream.write(string.toByteArray())
            outputStream.close()
            Toast.makeText(applicationContext, "file.txt가 생성됨.", Toast.LENGTH_SHORT).show()
        }

        btnRead.setOnClickListener {
            try {
                val inputStream = openFileInput("file.txt")
                val txt = ByteArray(30)
                inputStream.read(txt)
                val string = txt.toString(Charsets.UTF_8)
                Toast.makeText(applicationContext, string, Toast.LENGTH_SHORT).show()
            } catch (e : Exception) {
                Toast.makeText(applicationContext, "파일 없음", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

 

val outputStream = openFileOutput("file.txt", Context.MODE_PRIVATE)


    ✓  file.txt로 파일을 쓰기 모드로 열기. 파일의 경로는 /data/data/패키지명/files/file.txt가 됨
    ✓  파일 모드에는 쓰기(write)를 위해 MODE_PRIVATE (생성한 앱에서만 사용 가능)나 MODE_APPEND (파일이 존재하는 경우 내용 추가) 등을 사용

  • MODE_PRIVATE : 혼자만 사용하는 모드
  • MODE_APPEND : 파일이 존재할 경우 기존내용에 추가하는 모드
  • MODE_WORLD_READABLE : 다른 응용 프로그램과 파일 읽을 수 있음
  • MODE_WORLD_WRITABLE : 다른 응용 프로그램이 파일 기록할 수 있음
val txt = ByteArray(30)
inputStream.read(txt)
val string = txt.toString(Charsets.UTF_8)

 

    ✓  byte[] 형 변수 txt에 입력 파일에서 읽어온 데이터를 저장. txt를 문자열로 변환.

 


 

2) raw 폴더 파일 처리


🐰  프로젝트의 /res/raw 폴더에 필요한 파일을 저장하기 위해 사용하는 방법
    📍 기본적으로 /res 아래에 raw 폴더를 생성하고 프로젝트에서 사용할 파일을 넣어둠


🐰  Java 코드에서 openRawResource() 메서드를 사용하여 접근할 수 있으며 FileInputStream 클래스 대신 InputStream 클래스를 사용
🐰  /res/raw는 프로젝트에 포함된 폴더이므로 읽기 전용으로만 사용 가능하고 쓰기는 할 수 없음. 쓰기에는 내장 메모리나 SD 카드를 사용해야 함.

 

프로젝트의 res 폴더에 raw 폴더를 생성하고, 임의의 내용을 입력한 *.txt파일을 복사
텍스트 파일은 UTF-8 형식으로 저장

 

xml 코드
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btnRead"
        android:text="/res/raw에서 파일 읽기" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editRaw"
        android:lines="10" />

</LinearLayout>

 

kotlin 코드
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_01)

        val btnRead = findViewById<Button>(R.id.btnRead)
        val editRaw = findViewById<EditText>(R.id.editRaw)

        btnRead.setOnClickListener {
            val inputStream = resources.openRawResource(R.raw.test)
            val txt = ByteArray(inputStream.available())
            inputStream.read(txt)
            editRaw.setText(txt.toString(Charsets.UTF_8))
            inputStream.close()
        }
    }
}

 

val inputStream = resources.openRawResource(R.raw.test)

 

   ✓  resources는 현재 패키지의 리소스를 반환. openRawResource()- /res/raw 파일을 읽기용으로 열기.

 

val txt = ByteArray(inputStream.available())


   ✓  inputStream.available() : 입력 스트림에서 읽을 수 있는 바이트 수를 반환. 결국 txt 파일의 크기 만큼 지정.

 

 

 

 

 

 

 

[ 내용 참고 : IT 학원 강의 ]

+ Recent posts