无法打开带有空白的Android文件名

无法打开带有空白的Android文件名,android,whitespace,filenames,Android,Whitespace,Filenames,在SD卡中打开文件时,我的代码正常工作。但是,如果我打开一个带有空格的文件名,则会出现错误(例如:Path-“/sdcard/download/hello hi.jpg”) 我尝试了string.replace(“,“%20”);它不起作用 try { File file = new File(paths); if (file.exists()) { Uri path = Uri.fromFile(file); Intent intent = ne

在SD卡中打开文件时,我的代码正常工作。但是,如果我打开一个带有空格的文件名,则会出现错误(例如:Path-“/sdcard/download/hello hi.jpg”)

我尝试了string.replace(“,“%20”);它不起作用

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();
}

请帮助

您需要逃离空间。尝试将“”替换为“\”

尝试:

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

Uri.parse
修复路径中的所有空白/反斜杠/非法字符问题,并生成一个“良好”Uri。

用如下空格替换%20

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

这对我有效

发生了什么错误?粘贴任何相关日志。不会出现错误。引发的异常没有消息。每个异常都有堆栈跟踪。它不会显示,因为您正在捕获所有异常并丢弃有价值的信息。将其插入catch块:Log.e(TAG,e.getMessage(),e);将logcat.java.lang.NullPointerException中打印的堆栈跟踪粘贴到oystor.app.Document.imglist.viewDocument(imglist.java:906)的oystor.app.Document.imglist.viewDoc(imglist.java:773)的oystor.app.Document.imglist$OrderAdapter$1。onClick(imglist.java:318)语法错误发生。无效的转义序列(有效的是\b\t\n\f\r\“\”\)
“foo bar”。替换(“,“\”);
谢谢显而易见的先生:不,说真的,你帮了我的忙。Uri.parse()在我的情况下不会删除空格。