Opening a textFile with the AssetManager and assigning it to a InputStream

388 Views Asked by At

Basically I think it could be a project structure issue as I'm unsure of where to put the textfile, I've made a directory assets and placed a folder called texts in that and in that have placed the myawesometext.txt.

The error I get is the exception being called that it could not find file.

I thought it could be to do with permissions but couldnt find a permissions related to it as its not external storage.

My question is if I have the file and im running the app where should I make an assets folder in the structure to be read I've double checked the spelling (no typos) it just catches my exception.

class:

public class AssetsTest extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    TextView textView = new TextView(this);
    setContentView(textView);
    AssetManager assetManager = getAssets();
    InputStream inputStream = null;
    try {
        inputStream = assetManager.open("texts/myawesometext");
        String text = loadTextFile(inputStream);
        textView.setText(text);
    } catch (IOException e) { textView.setText("Couldn't load file");
    } finally {
        if (inputStream != null)
            try { inputStream.close();
            } catch (IOException e) { textView.setText("Couldn't close file");
            } }
}
    public String loadTextFile(InputStream inputStream) throws IOException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); byte[] bytes = new byte[4096];
        int len = 0;
        while ((len = inputStream.read(bytes)) > 0) byteStream.write(bytes, 0, len);
        return new String(byteStream.toByteArray(), "UTF8"); }
}

location of file

Thanks in Advance... Ben

1

There are 1 best solutions below

2
On BEST ANSWER

Your assets folder location is not correct and your code is not correct as well. Please follow the following steps.

First, move the current assets folder to src/main.

screenshot

Second, change this line in your code from

inputStream = assetManager.open("texts/myawesometext");

to

inputStream = assetManager.open("texts/myawesometext.txt");