我想使用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");
错误:
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)
答案 0 :(得分:2)
尝试将.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");