-2

I have kept some binary files in raw directory in Android application. I want to access them in the application and create a file from it at runtime. I am going to send this file over network.

How can I refer the raw resources? I have done following code

private File getFileByResourceId(int id, String fileName) throws IOException {
        File file = new File(fileName);
        InputStream ins = ctx.openRawResource(id);
        log.debug(ins.toString());
        log.debug(file.getAbsolutePath());
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int size = 0;
        // Read the entire resource into a local byte buffer.
        byte[] buffer = new byte[1024];
        while ((size = ins.read(buffer, 0, 1024)) >= 0) {
            outputStream.write(buffer, 0, size);
        }
        ins.close();
        buffer = outputStream.toByteArray();
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(buffer);
        fos.close();
        return file;}

But when I try to access this file it gives me permission errors.

Can someone propose a solution?

Shiv Anand
  • 81
  • 1
  • 2
  • 10
  • Also please note the code is in a separate class where there is no context of Android. – Shiv Anand May 24 '17 at 12:12
  • Possible duplicate of [How to read file from res/raw by name](https://stackoverflow.com/questions/15912825/how-to-read-file-from-res-raw-by-name) – TT-- Dec 18 '18 at 17:02

1 Answers1

0

You have add this permision in Manifestfile

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

you are using Marshmallow os then you need to add runtime permission

public boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG, "Permission is granted");
            return true;
        } else {

            Log.v(TAG, "Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    } else { //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG, "Permission is granted");
        return true;
    }
}
Ratilal Chopda
  • 4,162
  • 4
  • 18
  • 31