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
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.
You need to escape the spaces. Try replacing " " with "\ "
Ashok Reddy
Replace %20 with space like below
filePath = filePath.replaceAll("%20"," ");
This worked for me
来源:https://stackoverflow.com/questions/9765384/android-filename-with-white-space-cannot-be-opened