javafilefilenotfoundexception

Java fileNotFoundException when accessing program files


I cannot seem to by pass this error for the life of me. In my previous post i was trying to update attributes to an xml file. I can read the file just fine, but when I try and write to it I get a file not found exception.

The program doesn't have a problem with reading the XML file and finding the attribute only writing to it. After trouble shooting this for awhile, it seems to be an issue with having the file in the Program Files directory. If I move the xml file to C:\Temp\test.xml I can write to it without any issues. As soon as it goes into a folder with any type of spaces it cannot seem to find it. Seems like an issue with the StreamResults.

        File file = new File(filePath); 
        document = documentBuilder.parse(file);
        NodeList sessionNodelist = document.getElementsByTagName("session");

      if (sessionNodelist.getLength() > 0)
        {
            Element sessionElement = (Element) sessionNodelist.item(0);
            sessionElement.setAttribute("timeout", "12");
            sessionElement.setAttribute("warning", "10");   
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(document);
            try{
            StreamResult result = new StreamResult(file);
            transformer.transform(source, result);
            }catch(Exception e)
            {   
                logger.info(e.getMessage());
            }
        }

java.io.FileNotFoundException: C:\Program%20Files\Test.xml (The system cannot find the path specified)

I am not exactly sure how to get around this error. You would think if it can read to it and find it in the first File call, the second file call should work right?

UPDATE: I tried some other methods.

So when i have the file path set to "C:\Program Files\test.xml" File.exists returns ture, along with read and writing. if I add the %20 to the program file path, they all return false" E.g C:\Program%20Files\test.xml.

So document = documentBuilder.parse(file); can parse the file just perfectly fine.

When StreamResults trys to open the file, it thoes the file not found error and displays the %20 in the Program files name.

StreamResult result = new StreamResult(file);
transformer.transform(source, result);

java.io.FileNotFoundException: C:\Program%20Files\Test.xml (The system cannot find the path specified)

Is there another way to stream the results to the xml file instead of StreamResults?


Solution

  • I figured it out. After doing a ton of reading about other people having a simular problem i had to do the following work around in order for it to work correctly.

      StreamResult result = new StreamResult(file.getPath());
      transformer.transform(source, result);
    

    It now works. Odd, but it works.