투케이2K

508. (kotlin/코틀린) [유틸 파일] createZipFile : zip 파일 생성 수행 본문

Kotlin

508. (kotlin/코틀린) [유틸 파일] createZipFile : zip 파일 생성 수행

투케이2K 2024. 6. 14. 16:41
반응형

[개발 환경 설정]

개발 툴 : AndroidStudio

개발 언어 : Kotlin

 

[소스 코드]

 

        // -----------------------------------------------------------------------------------------
        // TODO [SEARCH FAST] : [Observable] : createZipFile : zip 파일 생성 수행
        // -----------------------------------------------------------------------------------------
        // TODO [호출 방법 소스 코드]
        // -----------------------------------------------------------------------------------------
        /*
        try {

            // [공용 저장소 다운로드 폴더 >> 특정 폴더 지정]
            var downLoadfilePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath
            downLoadfilePath += "/LOG_SAVE_FOLDER/"

            // [생성할 Zip 파일 명칭]
            val zipPath = downLoadfilePath + "output.zip"

            // [압축할 대상의 자식 파일 명칭]
            val filePaths = Arrays.asList(
                downLoadfilePath + "APP_CRASH_LOG.txt",
                downLoadfilePath + "APP_USE_LOG.txt"
            )

            C_App.createZipFile(A_Intro@this, zipPath, filePaths)
                .subscribeOn(AndroidSchedulers.mainThread()) // [Observable (생성자) 로직을 IO 스레드에서 실행 : 백그라운드]
                .observeOn(Schedulers.io()) // [Observer (관찰자) 로직을 메인 스레드에서 실행]
                .subscribe(
                    { value ->
                        S_Log.ltw("================================================")
                        S_Log.cnt("[VALUE :: $value]")
                        S_Log.lbw("================================================")
                    },
                    { error ->
                        S_Log.lte("================================================")
                        S_Log.cnt("[ERROR :: " + error.message.toString() + "]")
                        S_Log.lbe("================================================")
                    }
                )
                {
                }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        */
        // -----------------------------------------------------------------------------------------
        fun createZipFile(mContext: Context, zipPath: String, childList: List<String>): Observable<Boolean> {

            // [로직 처리 실시]
            return Observable.create { subscriber: ObservableEmitter<Boolean> ->

                /**
                 * // -----------------------------------------
                 * [createZipFile 메소드 설명]
                 * // -----------------------------------------
                 * 1. zip 파일 생성 수행
                 * // -----------------------------------------
                 * 2. 리턴 데이터 : zip 파일 생성 성공 시 true / 문제 발생 시 false
                 * // -----------------------------------------
                 * 3. 추가로 외부 저장소에 파일 읽기 및 쓰기를 위해서 Manifest 권한 필요 및 인텐트 이동 수행
                 *
                 * 권한 : <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"></uses-permission>
                 *
                 * 인텐트 이동 : Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION
                 * // -----------------------------------------
                 * 4. 참고 설명 [1] :
                 *
                 * MANAGE_EXTERNAL_STORAGE 권한을 추가 시 마켓에 특정 용도로 사용하는 앱 목적을 밝혀야합니다
                 * (앱 등록 및 업데이트 리젝 될 수 있습니다)
                 *
                 * 외부 저장소 경로 : /storage/emulated/0
                 * // -----------------------------------------
                 * 5. 참고 설명 [2] :
                 *
                 * - 안드로이드 하위 (os 11 이하) 인 경우 외부 저장소 읽기 , 쓰기 권한 부여 필요
                 * - 안드로이드 상위 (os 11 이상) 인 경우 AndroidManifest.xml 파일에서 MANAGE_EXTERNAL_STORAGE 권한 부여 수행
                 * - 안드로이드 외부 저장소 접근 권한이 없는 경우는 앱 내부 캐시 저장소에 파일 저장 후 zip 파일 생성 수행
                 * // -----------------------------------------
                 */

                S_Log._D_("Zip 파일 생성 수행", arrayOf("zipPath :: $zipPath", "childList :: " + childList.toString()))

                try {

                    // [인풋 데이터 방어 로직 작성]
                    if (C_Util.stringNotNull(zipPath) === true && childList != null && childList.size > 0) {

                        // [안드로이드 버전 제한]
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // [오레오 이상]

                            // [반복문을 수행하면서 자식 리스트 추가 실시]
                            ZipOutputStream(FileOutputStream(zipPath)) // [Zip 파일 만들기 정의]
                                .use { zipOut ->
                                    for (filePath in childList) {
                                        val fileToZip = File(filePath) // [자식 File 확인]
                                        zipOut.putNextEntry(ZipEntry(fileToZip.name)) // [Zip 파일에 자식 추가]
                                        Files.copy(fileToZip.toPath(), zipOut) // [Zip 파일 경로로 자식 복사]
                                    }
                                    S_Log._W_("Zip 압축 파일 생성 성공", null)

                                    // [리턴 반환]
                                    subscriber.onNext(true)
                                    subscriber.onComplete()
                                }

                        } else {
                            subscriber.onError(Throwable("[Error] : Android Version Issue"))
                            subscriber.onComplete()
                        }
                    } else {
                        subscriber.onError(Throwable("[Error] : Input Data Is Null"))
                        subscriber.onComplete()
                    }

                } catch (e: Exception) {
                    e.printStackTrace()
                    try {
                        subscriber.onError(Throwable("[Exception] : [catch] : $e"))
                        subscriber.onComplete()
                    } catch (ex: Exception) {
                        ex.printStackTrace()
                    }
                }
            }
        }

 

반응형
Comments