Home > Software design >  Can't get path from Raw folder - java.nio.file.NoSuchFileException
Can't get path from Raw folder - java.nio.file.NoSuchFileException

Time:10-22

I'm trying to get the path to .txt file inside my res/raw folder but I keep getting a NoSuchFileException and I'm unsure what I'm doing incorrectly.

public static final String PATH_TO_BINARY_CONTRACT = "android.resource://com.example.testproject/raw/binary_code";

Uri uri = Uri.parse(Constants.PATH_TO_BINARY_CONTRACT);
        try {
            byte[] encoded = Files.readAllBytes(Paths.get(uri.getPath()));
        }catch (Exception e){
            Log.e(TAG, "onCreate: ", e);
        }

This keeps throwing a java.nio.file.NoSuchFileException: /raw/binary_code

What am I doing incorrectly?

CodePudding user response:

I'm trying to get the path to .txt file inside my res/raw folder

There is no path. A resource is a file on your development machine. It is not a file on the device.

To read in the contents of a raw resource, call openRawResource() on a Resources object. You get a Resources object by calling getResources() on any Context.

CodePudding user response:

Try this:

Uri pathUri = new Uri.Builder()
                     .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
                     .authority(context.getPackageName())
                     .path(String.valueOf(R.raw.binary_code))
                     .build();

Then use this:

File file = new File(pathUri.getPath());  //create path from uri

But I still don't understand why you would want to do this. I haven't tried this yet. But I got the Uri of a .ogg file in my res/raw folder like this. But it should work for you.

  • Related