简体   繁体   中英

reading resource as InputStream in android

I have some android project and I am trying to read some file from the "res/drawable-xhdpi" directory so I put

InputStream is = null;

        try {
            is = getResources().openRawResource(R.drawable.my_btn); //my_btn is inside drawable-xhdpi directory
        } catch (Exception e) {
            e.printStackTrace();
        }

but I get

error opening trace file: No such file or directory 

How can I deal with this issue. I tried to read this directly from FileInputStream with an absolute path, then I realized that the root from which the files are fetched is the root of the JVM so I still got the same No such file or directory error message

Update :

I added an assets directory in side src/main , then I put my_btn.png inside it then I call inside my MainActivity class

InputStream is = null;

        try {

            is = getAssets().open("my_btn.png");

        } catch (Exception e) {
            e.printStackTrace();
        }

but I still get the same error

The drawable will be fetched from "res/drawable-xhdpi" only if you are running the app on an xhdpi device. Else it will try to fetch the drawable from the corresponding drawable folder according to the screen and if it is not there, you will get the same error as above. If you are not sure which screen size you are using the best work around is to create a directory named "drawable" inside the res folder(ie, "res/drawable" ) and then add my_btn into the newly created "drawable" folder. Then it will fetch the image from the new folder regardless of the screen size.

EDIT

You are using the raw folder, not the resource folder. openRawResource reads from the raw folder. Use the following code to get a drawable and convert it to input stream(You will have to surround with try-catch).

Drawable drawable = getResources().getDrawable(R.drawable.my_btn);
BitmapDrawable bitmapDrawable = ((BitmapDrawable) drawable);
Bitmap bitmap = bitmapDrawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, stream); //use the compression format of your need
InputStream is = new ByteArrayInputStream(stream.toByteArray());

_pm.iconStream = getResources()。openRawResource(+ R.drawable.pdf_icon);

I am just trying to test and I take a picture and send it to Parse

Put your test image somewhere either in res/raw/ (then, use your existing code, with R.raw.whatever_you_call_the_image ) or in assets/ (then, use getAssets().open() with a relative path within assets/ to your image).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM