Manoharan
Manoharan

Reputation: 715

Android filename with white space cannot be opened

My code works correctly while opening a file in sdcard. However, if I open a filename with white space then error occurs (example: Path - "/sdcard/download/hello hi.jpg").

I tried string.replace(" ","%20"); it doesn't work

try {
    File file = new File(paths);
    if (file.exists()) {
        Uri path = Uri.fromFile(file);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(paths));

        if (!mimeType.equals("")) {
            intent.setDataAndType(path, mimeType);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        } else {
            Toast.makeText(this, "Unsupported Format to Open", Toast.LENGTH_SHORT).show();
        }
    }
} catch (ActivityNotFoundException e) {
    Toast.makeText(this, "No Application Available to View this File", Toast.LENGTH_SHORT).show();
} catch(Exception e) {
    Toast.makeText(this, "Error Occurred", Toast.LENGTH_SHORT).show();
}

Please help

Upvotes: 6

Views: 8600

Answers (3)

Ashok Reddy Narra
Ashok Reddy Narra

Reputation: 577

Replace %20 with space like below

filePath =  filePath.replaceAll("%20"," ");

This worked for me

Upvotes: 1

grebulon
grebulon

Reputation: 7982

Try:

Uri uri = Uri.parse(paths);
File file = new File(uri.getPath());

Uri.parse fixes all the whitespace/backslash/illegal character issues in paths and produces a "good" uri.

Upvotes: 13

Chris Thompson
Chris Thompson

Reputation: 35598

You need to escape the spaces. Try replacing " " with "\ "

Upvotes: 4

Related Questions