What is the best way to download files and save them to different folders within the android Assets?

Asked

Viewed 444 times

-1

Tree folder

What is the best way to download pdf files and save them to different folders within Android Assets folder?

For example, in folder A I will have 10 specific files, in folder B 20 specific files, so I need to check first if the files exist in the respective folders and if negative make the downloads.

What’s the best way to do that?

  • you probably won’t be able to save inside the Assets folder.

1 answer

2


Cannot save a file inside the folder assets after already packaged and generated the APK, as it is read only. See here in the documentation of Android existing storage options.

However, if you want to check whether a file already exists within the assets before making download for another folder, would be possible through the file name. For example, see this method below which you are checking if there is already a file inside the assets passing the context and a specific name as parameter:

public static boolean existFileInAsset(Context context, String file) {
    try {
        InputStream stream = context.getAssets().open("file:///android_asset/" + file);
        stream.close();
        return true;
    } catch (IOException e) {
       return false;
    }
}  

Therefore, just check this way below:

if(existFileInAsset(context,"jonsnow.pdf")){
    // aqui exibe qualquer mensagem considerando que o arquivo existe
} else {
    // aqui você pode colocar algum código para fazer download do arquivo 
    // pois se entrou aqui, é porque não existe o arquivo salvo com este nome.
}

In the Kotlin would look like this:

fun existFileInAsset(context: Context, file: String): Boolean {
    try {
        val stream = context.assets.open("file:///android_asset/" + file)
        stream.close()
        return true
    } catch (e: IOException) {
        return false
    }
}

To use this function in Kotlin, follow the same JAVA logic.

  • To leave a little more "kotlinizado" would be a good use extension, something like: fun Context.existFileInAsset(file: String)...

  • 1

    Thanks for the clarification.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.