반응형

File IO

설명

  • 안드로이드는 애플리케이션 데이터를 저장할 수 있는 저장소를 두 가지로 제공하고 있다.
  • 내부 저장소
    • 해당 애플리케이션을 통해서만 접근 가능
  • 외부 저장소
    • 모든 애플리케이션이 접근 가능. 탐색기를 통해 접근 가능한 영역
    • 외부 저장소 컨트롤을 위해 권한 획득 필요

코드

manifests/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android_example">

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Androidexample">
        <activity android:name=".MainActivity">
            <intent-filter>
                <!-- Entry Point -->
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/writeToPrivateStorageButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="write to private storage" />

    <Button
        android:id="@+id/readFromPrivateStorageButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="read from private storage" />

    <Button
        android:id="@+id/writeToExternalStorageButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="write to external storage" />

    <Button
        android:id="@+id/readFromExternalStorageButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="read from external storage" />

</LinearLayout>
MainActivity
class MainActivity : AppCompatActivity() {
    private val permissionList = arrayOf(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )

    private var path: String? = null

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

        checkPermission()

        path =
            Environment.getExternalStorageDirectory().absolutePath + "/android/data/" + packageName

        val file = File(path)
        if (!file.exists()) {
            file.mkdirs()
        }

        val writeToPrivateStorageButton = findViewById<Button>(R.id.writeToPrivateStorageButton)
        val readFromPrivateStorageButton = findViewById<Button>(R.id.readFromPrivateStorageButton)
        val readFromExternalStorageButton = findViewById<Button>(R.id.readFromExternalStorageButton)
        val writeToExternalStorageButton = findViewById<Button>(R.id.writeToExternalStorageButton)

        writeToPrivateStorageButton.setOnClickListener {
            try {
                val output = openFileOutput("myFile.dat", Context.MODE_PRIVATE)
                val dos = DataOutputStream(output)

                dos.writeInt(100)
                dos.writeDouble(33.33)
                dos.writeUTF("Hello")
                dos.flush()
                dos.close()

                Toast.makeText(this, "저장 완료", Toast.LENGTH_SHORT).show()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        readFromPrivateStorageButton.setOnClickListener {
            try {
                val input = openFileInput("myFile.dat")
                val dis = DataInputStream(input)
                val value1 = dis.readInt()
                val value2 = dis.readDouble()
                val value3 = dis.readUTF()
                val message = "${value1}, ${value2}, ${value3}"
                dis.close()

                Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        writeToExternalStorageButton.setOnClickListener {
            try {
                val output = FileOutputStream("$path/sdFile.dat")
                val dos = DataOutputStream(output)
                dos.writeInt(200)
                dos.writeDouble(55.55)
                dos.writeUTF("Hi")
                dos.flush()
                dos.close()

                Toast.makeText(this, "저장 완료", Toast.LENGTH_SHORT).show()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        readFromExternalStorageButton.setOnClickListener {
            try {
                val input = FileInputStream("$path/sdFile.dat")
                val dis = DataInputStream(input)
                val value1 = dis.readInt()
                val value2 = dis.readDouble()
                val value3 = dis.readUTF()
                val message = "${value1}, ${value2}, ${value3}"
                dis.close()

                Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun checkPermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return
        }

        for (permission: String in permissionList) {
            val check = checkCallingOrSelfPermission(permission)

            if (check == PackageManager.PERMISSION_DENIED) {
                requestPermissions(permissionList, 0)
                break
            }
        }
    }
}

참고

반응형

'Development > Android' 카테고리의 다른 글

[Android] Lottie  (0) 2021.02.09
[Android] Http Network  (0) 2021.02.09
[Android] Permission  (0) 2021.02.09
[Android] Notification  (0) 2021.02.09
[Android] Application  (0) 2021.02.09

+ Recent posts