Sora
Sora

Reputation: 2551

File not found exception when trying to read from uri in android

i want to read a fileInputStream from uri but it is returning a file not found exception

this is my code so far :

 Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE);
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(getContext(), "Please install a File Manager.", Toast.LENGTH_SHORT).show();
    }

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case FILE_SELECT_CODE:
            if (resultCode == RESULT_OK) {
                // Get the Uri of the selected file
                Uri fileUri = data.getData();
               long size = Helper.GetFileSize(getActivity(),fileUri);
                File F = new File(fileUri.getPath());
                Log.d("File", "File Uri: " + fileUri.toString());
                FileInputStream fis;
                try {
                    fis = new FileInputStream(new File(F.getPath()));
                }
                 catch (Exception ex) {
                     ex.printStackTrace();
                }
            }
            break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

Upvotes: 0

Views: 2221

Answers (1)

sumandas
sumandas

Reputation: 565

The issue is the path contains content://.... whereas File needs to have an actual filePath

Try to update this bit in your code snippet:

 Uri fileUri = data.getData();
 String filePath = getPathFromUri(this,fileUri);
 long size = Helper.GetFileSize(getActivity(),filePath);
 File F = new File(filePath);

and this is the method to help

 public String getPathFromURI(Context context, Uri contentUri) {
   Cursor mediaCursor = null;
   try { 
           String[] dataPath = { MediaStore.Images.Media.DATA };
           mediaCursor = context.getContentResolver().query(contentUri,  dataPath, null, null, null);
           int column_index = mediaCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
           mediaCursor.moveToFirst();
           return mediaCursor.getString(column_index);
   } finally {
       if (mediaCursor != null) {
             mediaCursor.close();
       }
   }
}

Upvotes: 2

Related Questions