Search code examples
androidandroid-file

How to read files at a specific path in android?


I am developing an application in which I open the file explorer and select any file of my choice and retrieve its contents. The default path that opens is /storage/sdcard0 . I am able to read contents of any file that resides directly in this path. However, for any file that in contained in any folder inside /storage/sdcard0/. is inaccessible. The program gives a file not found error. Also, I cannot understand the path that these files have, like for example, if a file resides in path:

/storage/sdcard0/DCIM/100ANDRO/DSC_0001.jpg

, the logcat shows the path to be:

content:/media/external/images/media/84290/DSC_0001.jpg

How to access this file in my Java code?

Below is the code snippet:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    Log.d(TAG, "requestCode received: "+requestCode+" result code: "+resultCode);

    if (requestCode == 1 && resultCode == RESULT_OK) {

        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        String folderPath = "Anant";
        String filePath = "image.jpg";

        String imagePath = saveToInternalStorage(thumbnail, folderPath,
                sImageName);

        Log.i(TAG, "DeviceAPIS:actual path :: "
                + imagePath.trim().toString());
        sendCameraData(imagePath.toString().trim(),
                ptrAppContainerForCamera);
    }

    else if (requestCode == REQUEST_PATH){
        if (resultCode == RESULT_OK) {
              // Get the Uri of the selected file
            Uri uri = data.getData();
            Log.d(TAG, "data.getData() result line 742: " + uri);
            String uriString = uri.toString();
            File myFile = new File(uriString);
            String path = myFile.getAbsolutePath();
            String base64 ="Error";
            byte[] bytesRead = base64.getBytes();
            String displayName = null;
            String fileName = null;

            if (uriString.startsWith("content://")) {               
                Cursor cursor = null;
                try {                           
                    cursor = mContext.getContentResolver().query(uri, null, null, null, null);                         
                    if (cursor != null && cursor.moveToFirst()) {                               
                        displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                        displayName = path + "/" + displayName;
                        Log.d(TAG, "BEFORE REPLACE: "+displayName);
                        int index = displayName.indexOf(':');
                        fileName = displayName.substring(index + 1, displayName.length());
                        Log.d(TAG,"displayName line 762 " + Part);
                    }
                } finally {
                    cursor.close();
                }
            } else if (uriString.startsWith("file://")) {
                Log.d(TAG, "FILE BLOCK LINE 768");           
                displayName = myFile.getName();
                Log.d(TAG,"displayName 11" + displayName);
            }


            try{
                File sdcard = Environment.getExternalStorageDirectory();
                File readFile = new File(sdcard, fileName);
        //      File readFile = new File(uri);

                int length = (int)readFile.length();

                byte[] bytes = new byte[length];

                FileInputStream in = new FileInputStream(readFile);
                try{
                    in.read(bytes);
                }finally {
                    in.close();
                }

                String contents = new String(bytes);
                Log.d(TAG,"contents read :: \\n"  + contents);

                //convert to Base64
                bytesRead = contents.getBytes("UTF-8");
                base64 = Base64.encodeToString(bytesRead,Base64.DEFAULT);

            }catch (Exception e){
                Log.d(TAG, "THROWING EXCEPTION");
                Log.e(TAG,e.getMessage(),e);
            }
        }

The exception thrown is java.io.FileNotFoundException. Any help is greatly appreciated.


Solution

  • You can try as below:

        String path = null;
        Uri originalUri = data.getData();
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            Cursor cursor = this.managedQuery(originalUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            path = cursor.getString(column_index);
        } catch (Exception e) {
    
        } finally {
            cursor.close();
        }
    

    And if path is null, you can get bitmap first and then copy it to your local path.

        ContentResolver resolver = this.getContentResolver();
        Bitmap photo = MediaStore.Images.Media.getBitmap(resolver, originalUri);
        .... // copy photo to your local path