skip to Main Content

I want to read the file during runtime in Kotlin function, the file I want to read is stored
at projectname/app/credentials.json and I want to read credentials.json.

similar case can be how firebase read its credential file google-services.json

PS: I don’t want to put file in assets as I have already figured assets method

3

Answers


  1. You can find your answers through this link
    https://stackoverflow.com/a/62878278/21735165

    You have to put the file into your assets folder and read it. Check out the link

    Login or Signup to reply.
  2. You Should use the Context openFileInput method that this method can get the file of app path. 
    
    val file:FileInputStream = context.openFileInput("credentials.json")
    Login or Signup to reply.
  3. In Kotlin, you can read a file from the filesystem using standard Java I/O operations. Here is a way you can read the "credentials.json" file located in your project directory:

    Run this code :

    import java.io.File
    
    fun readCredentials(): String? {
        val filePath = "app/credentials.json" 
        val file = File(filePath)
        return if (file.exists()) {
            file.readText()
        } else {
            null
        }
    }
    
    fun main() {
        val credentials = readCredentials()
        println(credentials)
    }
    

    Adjust the filePath variable to the correct relative path based on your project structure. This code will read the contents of "credentials.json" and return it as a string and if the file doesn’t exist, it will return null values.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search