1

For the past couple of days, I've been trying to figure out what I'm doing wrong. Whenever the user uploads a file (non-image), and I try to convert the URI object into a file and then into a byte array, I get this error:

java.io.FileNotFoundException: /document/2301 (No such file or directory)

I had obviously uploaded something because it was showing me some sort of path. Here is my code:

MAIN ACTIVITY-

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.MediaFormat;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);

        } else {

            getFile();

        }
    }

    public void getFile() {

        Intent intent = new Intent();
        intent.setType("application/pdf");
        intent.setAction(Intent.ACTION_GET_CONTENT);

        startActivityForResult(intent, 1);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1) {

            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                getFile();

            }


        }

    }


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

        if (requestCode == 1 && resultCode == RESULT_OK && data != null) {

            Uri selectedFile = data.getData();

            Log.i("Path", selectedFile.getPath());

            File file = new File(selectedFile.getPath());

            byte[] b = new byte[(int) file.length()];
            try {
                FileInputStream fileInputStream = new FileInputStream(file);
                fileInputStream.read(b);
                for (int i = 0; i < b.length; i++) {
                    System.out.print((char)b[i]);
                }
            } catch (FileNotFoundException e) {
                System.out.println("File Not Found.");
                e.printStackTrace();
            }
            catch (IOException e1) {
                System.out.println("Error Reading The File.");
                e1.printStackTrace();
            }

        }

    }
}

Any sort of help is appreciated!

  • possible duplicate of https://stackoverflow.com/questions/16791439/android-how-to-get-uri-from-raw-file?rq=1 – Ivan Pronin Jul 09 '17 at 20:07
  • @IvanPronin I fail to see how this is a duplicate. – TheFiveHundredYears Jul 09 '17 at 20:24
  • Try this approach, use `getResources().openRawResource(ResourceID)` as your inputStream - see the accepted answer – Ivan Pronin Jul 09 '17 at 20:26
  • @IvanPronin But I'm not importing raw files, I'm using an Intent to get it from the user. – TheFiveHundredYears Jul 09 '17 at 20:59
  • Try this: remove all special characters and spaces from filename and make it short and simple. Then move it to /emulate/0 to shorten the path. – Ali Jul 09 '17 at 22:46
  • @Ali No special characters or spaces in the filename I chose. I'm trying to figure out how to move it to the parent folder now. – TheFiveHundredYears Jul 09 '17 at 23:21
  • @Ali It worked! But, how can I solve this issue without moving all of my files/user's files to emulated/0/? – TheFiveHundredYears Jul 09 '17 at 23:27
  • what does Log.i("Path", selectedFile.getPath()); print on LogCat? – Ali Jul 10 '17 at 01:26
  • @Ali '/document/2530' , the '2530' corresponding to whatever file I choose. The folder 'document' doesn't exist on my phone (at least not according to my file manager), so I don't know what it means. – TheFiveHundredYears Jul 10 '17 at 01:39
  • where does file '2530' actually exist? – Ali Jul 10 '17 at 01:45
  • @Ali It doesn't - anywhere. I can only access the file if it is placed in the storage/emulated/0 folder, or in one of my actual folders. Perhaps, since I use a Google Pixel, the fact that I open up the file from Drive automatically throws it off? So maybe 'documents' is just a folder created by Drive, and is inaccessible to me? – TheFiveHundredYears Jul 10 '17 at 01:48

2 Answers2

4

The file does not exist on Internal Storage. Use below code to solve the issue.

 public static String getPath(Context context, Uri uri) {
    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }
            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {
            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else
        if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }
            final String selection = "_id=?";
            final String[] selectionArgs = new String[] {split[1]};
            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }
    return null;
}

public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = { column };
    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
        if (cursor != null && cursor.moveToFirst()) {
            final int index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}

public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is Google Photos.
 */
public static boolean isGooglePhotosUri(Uri uri) {
    return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}

Use the below code to browse the file in any format.

    public void browseClick() {

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    //intent.putExtra("browseCoa", itemToBrowse);
    //Intent chooser = Intent.createChooser(intent, "Select a File to Upload");
    try {
        //startActivityForResult(chooser, FILE_SELECT_CODE);
        startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"),FILE_SELECT_CODE);
    } catch (Exception ex) {
        System.out.println("browseClick :"+ex);//android.content.ActivityNotFoundException ex
    }
}

Then get that file path in the onActivityResult like below.

    @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == FILE_SELECT_CODE) {
        if (resultCode == RESULT_OK) {
            try {
              Uri uri = data.getData();

                if (filesize >= FILE_SIZE_LIMIT) {
                    Toast.makeText(this,"The selected file is too large. Selet a new file with size less than 2mb",Toast.LENGTH_LONG).show();
                } else {
                    String mimeType = getContentResolver().getType(uri);
                    if (mimeType == null) {
                        String path = getPath(this, uri);
                        if (path == null) {
                            filename = FilenameUtils.getName(uri.toString());
                        } else {
                            File file = new File(path);
                            filename = file.getName();
                        }
                    } else {
                        Uri returnUri = data.getData();
                        Cursor returnCursor = getContentResolver().query(returnUri, null, null, null, null);
                        int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                        int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
                        returnCursor.moveToFirst();
                        filename = returnCursor.getString(nameIndex);
                        String size = Long.toString(returnCursor.getLong(sizeIndex));
                    }
   File fileSave = getExternalFilesDir(null);
    String sourcePath = getExternalFilesDir(null).toString();
    try {
                        copyFileStream(new File(sourcePath + "/" + filename), uri,this);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
  }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
private void copyFileStream(File dest, Uri uri, Context context)
        throws IOException {
    InputStream is = null;
    OutputStream os = null;
    try {
        is = context.getContentResolver().openInputStream(uri);
        os = new FileOutputStream(dest);
        byte[] buffer = new byte[1024];
        int length;

        while ((length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);

        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        is.close();
        os.close();
    }
}

After this you can open this file from your application external storage where you saved the file with appropriate action.

Courtesy: https://stackoverflow.com/a/36129285/6050536

Ali
  • 839
  • 11
  • 21
  • I replaced 'data.getData()' with 'data.getData().toString()' since it required a String value, but nothing changed. Whenever I check selectedFile.getPath(), it comes up with '/document/#somenumber#' -- any idea what this means? I don't have a 'document' folder on my phone. – TheFiveHundredYears Jul 10 '17 at 01:40
  • Thanks! One thing, though, is FilenameUtils still a valid reference? It seems like it no longer exists. – TheFiveHundredYears Jul 10 '17 at 02:32
  • 1
    Yes, you can use it or this to get file name: uri.toString().substring(uri.toString().lastIndexOf("/")+1); – Ali Jul 10 '17 at 02:43
  • Really? It's giving me an error. EDIT: I'm trying your new solution – TheFiveHundredYears Jul 10 '17 at 02:48
  • compile 'org.apache.commons:commons-io:2.5' contains FileUtils class. You can add it to your dependencies. – Ali Jul 10 '17 at 02:54
  • For the love of God, Thank you!!! This fixed a 6hr problem. I spent so much time trying to access the file and didn't even think about trying to copy it to somewhere else. Bless you mate! – NaturallyAsh Aug 10 '20 at 04:34
2
private String fileToBase64Conversion(Uri file) {
        InputStream inputStream = null;//You can get an inputStream using any IO API
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try {
            inputStream = context.getContentResolver().openInputStream(file);
            byte[] buffer = new byte[8192];
            int bytesRead;
            Base64OutputStream outputBase64 = new Base64OutputStream(output, Base64.DEFAULT);
            try {
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputBase64.write(buffer, 0, bytesRead);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            outputBase64.close();
        } catch (Exception ex) {

        }

        return outputBase64.toString();
    }
Saurabh Bhandari
  • 340
  • 3
  • 11