unable access assets file android

时间:2016-06-18 20:14:28

标签: android pdf assets

Hi I am developing android application in which I have assets folder. Inside assets folder I have put abc.pdf. But when I tried to access that file it shows me file not exists. I tried it in following way.

 File pdfFile = new File("file:///android_asset/"+ "abc.pdf");
    if(!pdfFile.exists()){
        Toast.makeText(this, "not there", Toast.LENGTH_SHORT).show();
        return;
    }
    else
    {
        Toast.makeText(this, "it's there", Toast.LENGTH_SHORT).show();
    }

Am I doing anything wrong? Need some help. Thank you.

2 个答案:

答案 0 :(得分:2)

An asset is only a file on your development machine. It is not a file on the device. You cannot reference it using File.

Use AssetManager and open() to get an InputStream on the asset. You can get an AssetManager by calling getAssets() on any Context or Resources object.

答案 1 :(得分:0)

For example, load json file from assets folder:

private String loadJSONFromAsset(Context context) {
    String json;
    try {
        AssetManager assetManager = context.getAssets();
        InputStream inputStream = assetManager.open("model.json");
        StringWriter writer = new StringWriter();
        IOUtils.copy(inputStream, writer, "UTF-8");
        json = writer.toString();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return json;
}