Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save file in Android with spaces in file name

I need for my android application to save an xml file into the external cache with a file name which contains space.

DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(activity
                    .getExternalCacheDir().getAbsolutePath()
                    + "/Local storage.xml"));

transformer.transform(source, result);

When I browse manually into my file directory I find this file : "Local%20storage.xml".

So after when I try to read it with

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

But I have a FileNotFoundException because the file "Local storage.xml" can't be found on my device.

Any ideas to solve this? Seb

like image 689
grattmandu03 Avatar asked Apr 24 '12 16:04

grattmandu03


1 Answers

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.

like image 176
grattmandu03 Avatar answered Sep 19 '22 02:09

grattmandu03