2012-03-19 31 views
2

我的代码在SD卡中打开文件时工作正常。但是,如果我用白色空格打开文件名,则会发生错误(例如:路径 - “/ sdcard/download/hello hi.jpg”)。无法打开Android空间的文件名

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

请帮

+0

那是什么发生了错误?粘贴任何相关日志。 – 2012-03-19 06:49:00

+0

没有错误即将到来。抛出的异常没有消息。 – Manoharan 2012-03-19 07:41:22

+0

每个异常都会有一个堆栈跟踪。它没有显示,因为你正在捕捉所有异常并丢弃有价值的信息。将它插入到catch块中:Log.e(TAG,e.getMessage(),e); – 2012-03-19 07:52:26

回答

4

你需要逃避的空间。尝试“用” \替换“”

+0

发生语法错误。无效的转义序列(有效的转义序列是\ b \ t \ n \ f \ r \“\'\\) – Manoharan 2012-03-19 07:41:41

+3

''foo bar”.replace(“”,“\\”);' – 2012-10-21 17:10:59

6

尝试:

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

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

+1

认为这很明显,但开始... – grebulon 2016-09-08 08:23:21

0

更换%20与空间像下面

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

这为我工作