安卓中带有空格的文件名无法打开

6

当我在sd卡中打开一个文件时,我的代码可以正常工作。但是,如果我打开一个带有空格的文件名,则会出现错误(例如:路径 - "/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();
}

请帮忙


发生了什么错误?请粘贴相关的日志。 - Dheeraj Vepakomma
没有出现任何错误。抛出的异常没有消息。 - Manoharan
每个异常都会有一个堆栈跟踪。它没有显示出来,因为您捕获了所有异常并丢弃了有价值的信息。在catch块中插入以下内容:Log.e(TAG, e.getMessage(), e); - Dheeraj Vepakomma
请粘贴在logcat中打印的堆栈跟踪。 - Dheeraj Vepakomma
java.lang.NullPointerException 在oystor.app.Document.imglist.java文件的viewDocument方法中的第906行 在oystor.app.Document.imglist.java文件的viewDoc方法中的第773行 在oystor.app.Document.imglist.java文件的OrderAdapter类的第1个元素的onClick方法中的第318行 - Manoharan
这个问题有没有有效的答案? - JohnA10
3个回答

13

尝试:

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

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


谢谢显而易见先生:D,不开玩笑,您帮了我大忙。 - CantThinkOfAnything
1
Uri.parse() 在我的情况下不会去除空格。 - lini sax

4

您需要对空格进行转义。请尝试使用"\ "代替" "。


发生语法错误。无效的转义序列(有效的序列是 \b \t \n \f \r " ' \)。 - Manoharan
3
"foo bar".replace(" ", "\\ "); 可以翻译为:将字符串 "foo bar" 中的空格替换为反斜杠和空格组成的字符串,即:"foo\ bar"。 - Vytautas Šaltenis

1

%20替换为空格,如下所示

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

这个对我有用


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接