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

Man*_*ran 4 filenames whitespace android

在sdcard中打开文件时,我的代码正常工作.但是,如果我打开带有空格的文件名,则会出现错误(例如:路径 - "/ 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();
}
Run Code Online (Sandbox Code Playgroud)

请帮忙

gre*_*lon 10

尝试:

Uri uri = Uri.parse(paths);
File file = new File(uri.getPath());
Run Code Online (Sandbox Code Playgroud)

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


Chr*_*son 4

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

  • `"foo bar".replace(" ", "\\ ");` (3认同)