如何在java中删除文件路径编码%20

Kar*_*hik 5 java xml windows filenotfoundexception filepath

我正在尝试使用 java 在特定路径中创建一个 xml 文件。问题是,如果我给出带有空格的文件路径,它会在空格中使用“ %20 ”进行编码。请帮助我解决这个问题。

我给出的文件路径 - “F:/Backup Files/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");
Run Code Online (Sandbox Code Playgroud)

错误:

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)
Run Code Online (Sandbox Code Playgroud)

Pli*_*kee 5

尝试添加.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");
Run Code Online (Sandbox Code Playgroud)