Android filename with white space cannot be opened

匆匆过客 提交于 2019-11-30 14:18:02

问题


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


回答1:


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.




回答2:


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




回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!