Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 658
Manoharan Avatar asked Mar 19 '12 05:03

Manoharan


People also ask

Is space allowed in filenames?

Don't start or end your filename with a space, period, hyphen, or underline. Keep your filenames to a reasonable length and be sure they are under 31 characters. Most operating systems are case sensitive; always use lowercase. Avoid using spaces and underscores; use a hyphen instead.

Do spaces in file names cause problems?

Spaces are not supported by all operating systems or by command line applications. A space in a filename can cause errors when loading a file or when transferring files between computers. Common replacements for spaces in a filenames are dashes (-) or underscores (_).

Can Java file names have spaces?

Java per se handles spaces in filenames just fine with no escaping or anything.


1 Answers

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.

like image 68
grebulon Avatar answered Oct 03 '22 22:10

grebulon