2017-04-22 34 views
1

我打算在使用java的特定路徑中創建一個xml文件。 問題是如果我給它的空間編碼的文件路徑是'%20'在空格中。 請幫我解決這個問題。由我給如何在java中刪除文件路徑編碼%20

文件路徑 - 「F:/備份文件/ testng2.xml」
編碼後 - 「F:/Backup%20Files/testng2.xml」

代碼:

TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
Transformer transformer = transformerFactory.newTransformer(); 
DOMSource source = new DOMSource(doc); 
StreamResult result = new StreamResult(new File("F:/Backup Files/testng2.xml"));  
transformer.transform(source, result); 
System.out.println("File saved successfully"); 

錯誤:

javax.xml.transform.TransformerException: java.io.FileNotFoundException: F:\Backup%20Files\testng2.xml (The system cannot find the path specified) 
    at org.apache.xalan.transformer.TransformerIdentityImpl.createResultContentHandler(TransformerIdentityImpl.java:297) 
    at org.apache.xalan.transformer.TransformerIdentityImpl.transform(TransformerIdentityImpl.java:330) 
    at FrameworkKeywords.ConfigurationFunctions.generateTestngXmlFile(ConfigurationFunctions.java:87) 
    at FrameworkKeywords.ConfigurationFunctions.main(ConfigurationFunctions.java:29) 
Caused by: java.io.FileNotFoundException: F:\Backup%20Files\testng2.xml (The system cannot find the path specified) 
    at java.io.FileOutputStream.open0(Native Method) 
    at java.io.FileOutputStream.open(Unknown Source) 
    at java.io.FileOutputStream.<init>(Unknown Source) 
    at java.io.FileOutputStream.<init>(Unknown Source) 
    at org.apache.xalan.transformer.TransformerIdentityImpl.createResultContentHandler(TransformerIdentityImpl.java:287) 
    ... 3 more 
--------- 
java.io.FileNotFoundException: F:\Backup%20Files\testng2.xml (The system cannot find the path specified) 
    at java.io.FileOutputStream.open0(Native Method) 
    at java.io.FileOutputStream.open(Unknown Source) 
    at java.io.FileOutputStream.<init>(Unknown Source) 
    at java.io.FileOutputStream.<init>(Unknown Source) 
    at org.apache.xalan.transformer.TransformerIdentityImpl.createResultContentHandler(TransformerIdentityImpl.java:287) 
    at org.apache.xalan.transformer.TransformerIdentityImpl.transform(TransformerIdentityImpl.java:330) 
    at FrameworkKeywords.ConfigurationFunctions.generateTestngXmlFile(ConfigurationFunctions.java:87) 
    at FrameworkKeywords.ConfigurationFunctions.main(ConfigurationFunctions.java:29) 

回答

1

嘗試增加.getAbsolutePath()File,如下所示:

TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
    Transformer transformer = transformerFactory.newTransformer(); 
    DOMSource source = new DOMSource(doc); 
    StreamResult result = new StreamResult(new File("F:/Backup Files/testng2.xml").getAbsolutePath());   
    transformer.transform(source, result); 
    System.out.println("File saved successfully"); 
+0

非常感謝@Plirkee。你的答案非常有用。它爲我工作。 – Baskar