0

I'm trying to convert a File to byte array format. The selected actual path is there in the storage, but still its throwing exception as "File Not Found". Can anyone help me to sort out this?

Thanks for your precious time!..

calling file manager

btn_click.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            startActivityForResult(intent, 7);

        }
    });

getting response

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub

 switch (requestCode) {
        case 7:

    if (resultCode == RESULT_OK) {

        String filePath = data.getData().getPath();
        System.out.println("====== path :   "+filePath);

        File file = new File(filePath);
        byte[] bytesArray = new byte[(int) file.length()];
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            fis.read(bytesArray); //read file into bytes[]
            fis.close();

            System.out.println("====== bytesArray    "+bytesArray);


        } catch (FileNotFoundException e) {
            System.out.println("====== File Not Found.");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("====== Error Reading The File. IOException");
            e.printStackTrace();
         }
      }
   }
}
manick k
  • 25
  • 10
  • See also [this similar question](https://stackoverflow.com/questions/35870825/getting-the-absolute-file-path-from-content-uri-for-searched-images). You are not working with files. Use `ContentResolver` and `openInputStream()` to get an `InputStream` on the content identified by the `Uri`. Do not attempt to use `getPath()`. – CommonsWare Mar 15 '18 at 13:06

1 Answers1

0

Add the following grade its Apache commons gradle

    compile 'org.apache.commons:commons-io:1.3.2'

then use this code

    byteArray = FileUtils.readFileToByteArray(file);  
Ramkumar.M
  • 681
  • 6
  • 21
  • I tried to use your suggestion, when Im trying to run the application, showing error as Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'. > com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex – manick k Mar 15 '18 at 13:00
  • any idea about this? – manick k Mar 15 '18 at 13:01
  • still its throwing "File not Found". but my file path location shows like /document/primary:file/myDoc_4.pdf. – manick k Mar 15 '18 at 14:48