package com.ama.core.architecture.util

import android.content.Context
import com.ama.core.architecture.BaseApp
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader


class FileUtil private constructor() {
    companion object {


        fun readAssetsFile(fileName: String, encoding: String = "UTF-8"): String? {
            return try {
                // 使用use关键字自动关闭资源
                BaseApp.appContext().assets.open(fileName).use { inputStream ->
                    InputStreamReader(inputStream, encoding).use { reader ->
                        val buffer = CharArray(1024)
                        val result = StringBuilder()
                        while (true) {
                            val bytesRead = reader.read(buffer)
                            if (bytesRead == -1) break
                            result.append(buffer, 0, bytesRead)
                        }
                        result.toString()
                    }
                }
            } catch (e: IOException) {
                e.printStackTrace()
                null
            }
        }

        /**
         * 逐行读取文本文件（适合处理大文件或需要按行处理的场景）
         */
        fun readTextFileLineByLine(context: Context, fileName: String, encoding: String = "UTF-8"): List<String> {
            return try {
                context.assets.open(fileName).use { inputStream ->
                    InputStreamReader(inputStream, encoding).use { reader ->
                        BufferedReader(reader).useLines { lines ->
                            lines.toList()
                        }
                    }
                }
            } catch (e: IOException) {
                e.printStackTrace()
                emptyList()
            }
        }




    }
}


