Android Kotlin : URI에서 파일명 및 확장자 추출하기

2022. 9. 8. 09:06[Android APP] feat. Kotlin/Kotlin 공부

개요

우선 기존에 Context 안에 플래그로 openFileOutput 함수에 전달하여 쓰던 방식이 안드로이드 정책상 막혀버렸다.

그래서 파일을 가져오면 content://로 시작하는 Content URI를 제공받게 된다.

아래 함수는 Content URI에서 파일명과 확장자를 추출하는 함수이다.

 

 

코드

1. getName(파일명 가져오는 함수)

//Uri to 파일명 추출 함수
private fun getName(uri: Uri?): String {
    val projection = arrayOf(MediaStore.Files.FileColumns.DISPLAY_NAME)
    val cursor = managedQuery(uri, projection, null, null, null)
    val column_index = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DISPLAY_NAME)
    cursor.moveToFirst()
    return cursor.getString(column_index)
}

Uri 넣어주면 파일명을 뽑게 된다.(Screenshot_220908_kkkk.jpg)

 

 

2. getFileExtension(파일의 타입을 구해주는 함수)

Uri를 넣어주면 파일의 타입을 추출한다.(png, pdf, jpg...)

//파일 확장자 추출 함수
fun getFileExtension(context : Context, uri: Uri): String? {
    val fileType: String? = context.contentResolver.getType(uri)
    return MimeTypeMap.getSingleton().getExtensionFromMimeType(fileType)
}
반응형