How to open a file in a raw folder on Android

I am using MultipartEntity and I am trying to access the file in the source folder. Here is the code:

MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart(new FormBodyPart("file", new FileBody(new File("test.txt")))); 

The test.txt file is located in the res / raw folder. When I execute the code, I get the following exception: FileNotFoundException: /test.txt: open failed: ENOENT (There is no such file or directory)

Can anyone help me with this?

+4
source share
2 answers

Unfortunately, you cannot create a File object directly from the source folder. You need to copy it to either your SD card or application cache.

you can get an inputstream for your file this way

  InputStream in = getResources().openRawResource(R.raw.yourfile); try { int count = 0; byte[] bytes = new byte[32768]; StringBuilder builder = new StringBuilder(); while ( (count = in.read(bytes,0, 32768)) > 0) { builder.append(new String(bytes, 0, count)); } in.close(); reqEntity.addPart(new FormBodyPart("file", new StringBody(builder.toString()))); } catch (IOException e) { e.printStackTrace(); } 
+8
source

You can put the file in the / res / raw directory where the file will be indexed and accessible by identifier in the R file:

 InputStream is = getResources().openRawResource(R.raw.test); System.out.println(is); 
+3
source

Source: https://habr.com/ru/post/1482621/


All Articles