Trouble with reading file from assets folder in Android

心不动则不痛 提交于 2019-12-17 20:30:58

问题


This question is with regards to this one. Since it is a specific question I moved that question by itself here. I have tried creating a text file, "foo.txt", an read it into my Activity doing:

File file = new File("/assets/foo.txt");
if ( file.exists() ){
    txtView.setText("Exists");
}
else{
    txtView.setText("Does not exist");
}

The "foo.txt" file is located in my assets folder and I have verified that it exists in the OS. My TextView always gets the text "Does not exist" from the code above. I have tried going

File file = new File("/assets/foo.txt");
Scanner in = new Scanner(file);

as well, but this produces the following inline error: "Unhandled exception type FileNotFoundException". Eclipse then suggest to involve try/catch, which removes the error but it doesn't work properly then either.

I have also tried setting my assets folder to "Use as source folder", but this does not make any difference. I have also tried using a raw folder as several people suggests to no use. I am out of options and really need help for this one. Should be easy...

Another try is to go

AssetManager assetManager = getResources().getAssets();
InputStream is = assetManager.open("assets/foo.txt");

but this produces the inline error in the second line: "Unhandled exception type IOException".


回答1:


I'm with CommonsWare in that case (that's the safe side :) ), but it should be:

AssetManager assetManager = getResources().getAssets();
InputStream inputStream = null;

    try {
        inputStream = assetManager.open("foo.txt");
            if ( inputStream != null)
                Log.d(TAG, "It worked!");
        } catch (IOException e) {
            e.printStackTrace();
        }

Do not use InputStream is = assetManager.open("assets/foo.txt");




回答2:


You do not access assets/ at runtime using File. You access assets/ at runtime using AssetManager, which you can get via getResources().getAssets().




回答3:


try this :

    private AssetManager am;
     am=getAssets();

     InputStream inputStream = null ;  
        try   
        {  
            inputStream = am.open("read.txt");  
        }   
        catch (IOException e) {}  


来源:https://stackoverflow.com/questions/9674815/trouble-with-reading-file-from-assets-folder-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!