What is the best way to download files and save them to different folders within the android assets? [closed]

-1

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

For example, in folder A I will have 10 specific files in folder B 20 specific files, so I need to first check if the files exist in their folders and if they do not do the downloads.

What is the best way to do this?

    
asked by anonymous 14.08.2017 / 21:31

1 answer

2

You can not save a file inside the assets folder after it has already been packaged and generated the APK because it is read-only. See the Android documentation existing storage options .

However, if you want to check if a file already exists within assets before downloading another folder, it would be possible through the filename . For example, see this method below in which you are checking whether a file already exists within assets by passing the context and a specific name as a 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;
    }
}  

So, 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.
}

No 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 logic as JAVA.

    
15.08.2017 / 00:30