Save file in Android with spaces in file name

喜欢而已 提交于 2019-12-05 11:11:26

It was hard to identify the source of this problem but it comes from StreamResult which replaces spaces in file name by %20. There is a bug report for this issue here.

And here is the solution :

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);

FileOutputStream fos = null;
try {
    fos = new FileOutputStream(new File(activity
                .getExternalCacheDir().getAbsolutePath()
                + "/" + "Local storage" + ".xml"));
    Result fileResult = new StreamResult(fos);
    transformer.transform(source, fileResult);
} catch (FileNotFoundException e) {
    e.printStackTrace();
} finally {
    if (fos != null) {
        fos.close();
    }
}

Thanks again to both of you for trying to solve my issue.

This works for me and is just one extra line of code

String fileName = "name with spaces" + ".xml";                  
fileName.replace(" ", "\\ ");

Try using basic URL encoding :

File localStorageXmlFile = new File(activity.getExternalCacheDir()
                .getAbsolutePath()
                + "/Local%20storage.xml");

This mgiht help you : URL encoding table

Also, when working with file, make sure you're using the right file separator for the OS (in your case the hard coded / should work since Android is linux based but just to make sure. This could be an other option :

File localStorageXmlFile = new File(activity.getExternalCacheDir()
                .getAbsolutePath() + File.separator 
                + "Local storage.xml");

Last resort optin would be to try to espace the space. Try replacing " " with "\ ".

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