![](/img/trans.png)
[英]in java my file paths with included spaces show up as %20 and i'm not sure why
[英]Transformer library that comes with Java converts spaces in file paths to %20
這是一個寫出XML文件的測試應用程序。
為什么路徑中的空格被轉換為%20
?
public class XmlTest
{
public static void main(String[] args)
{
String filename = "C:\\New Folder\\test.xml";
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource source = new DOMSource(doc);
File xmlFile = new File(filename);
if (xmlFile.exists())
{
xmlFile.delete();
}
StreamResult result = new StreamResult(xmlFile);
transformer.transform(source, result);
}
catch (ParserConfigurationException ex)
{
ex.printStackTrace();
}
catch (TransformerException tfe)
{
tfe.printStackTrace();
}
}
}
堆棧跟蹤:
java.io.FileNotFoundException: C:\New%20Folder\test.xml (The system cannot find the path specified)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:179)
at java.io.FileOutputStream.<init>(FileOutputStream.java:70)
at org.apache.xalan.transformer.TransformerIdentityImpl.createResultContentHandler(TransformerIdentityImpl.java:287)
at org.apache.xalan.transformer.TransformerIdentityImpl.transform(TransformerIdentityImpl.java:330)
at avm.trans.xml.XmlTest.main(XmlTest.java:52)
嘗試更改此行:
StreamResult result = new StreamResult(xmlFile);
進入這個:
StreamResult result = new StreamResult(new FileOutputStream(xmlFile));
我不知道,為什么文件名作為URL處理。
根據@ChristianKuetbach的回答,似乎傳遞給StreamResult
構造函數的參數決定了它將如何處理。
來自Oracle文檔
public StreamResult(String systemId)
Construct a StreamResult from a URL.
Parameters:
systemId - Must be a String that conforms to the URI syntax.
public StreamResult(File f)
Construct a StreamResult from a File.
Parameters:
f - Must a non-null File reference.
所以最初,我傳遞了一個String
路徑,因此大概是StreamResult
決定主動自動編碼,而不是假設它是“符合URI語法的字符串”。
因此,傳入File
對象會告訴它將其作為文件路徑而不是URL處理,因此空格(和其他特殊字符)不會被編碼。
在包含特殊字符的路徑的情況下也可能出現此問題,對此第一個答案幾乎沒有幫助(轉換,即)。 例如,在我的情況下,我的文件的路徑包含自動轉換為“%60”的字符“`”。
我通過更改代碼行解決了我的問題:
StreamResult result = new StreamResult(xmlFile);
result = D:/ Work /.../%60Projects /.../ xmlFile.xml
進入代碼行:
StreamResult result = new StreamResult(xmlFile);
result.setSystemId(URLDecoder.decode(xmlFile.toURI().toURL().toString(), "UTF-8"));
result = D:/ Work /.../`Projects /.../ xmlFile.xml
這將覆蓋StreamResult類中默認實現的URL編碼問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.