Search code examples
androidinputstreamassets

What is the best approach to open a TXT file from assets and read a string?


I need to check if a txt file exists on assets folder, and if exists I need to read the text of it and put into a string.

I saw some approaches on Google to open files from assets but I can't find one that gives you the possibility to check if the file exists and then read a string from it (because is a text resource).


Solution

  • You can just handle the exception properly when the file isn't found like this :

    try {
    
        InputStream is = SplashscreenActivity.this.getAssets().open("yourTextFile.txt");
    
    } catch (IOException e) {
        // catch your exception properly when the file isn't found
    }