java.net.URISyntaxException

我有这个例外。 但这个例外不再重现。 我想得到这个原因

Exception Caught while Checking tag in XMLjava.net.URISyntaxException: Illegal character in opaque part at index 2: C:\Documents and Settings\All Users\.SF\config\sd.xml stacktrace net.sf.saxon.trans.XPathException. 

为什么发生这种exception。 如何处理,所以它不会重现。

基本上"C:\Documents and Settings\All Users\.SF\config\sd.xml"是路径名,而不是有效的URI。 如果要将路径名转换为“file:”URI,请执行以下操作:

 File f = new File("C:\Documents and Settings\All Users\.SF\config\sd.xml"); URI u = f.toURI(); 

这是将路径名转换为Java中的有效URI的最简单,最可靠和最便携的方法。

但是您需要意识到“file:”URI有许多警告,如File.toURI()方法的javadoc中所述。 例如,在一台机器上创建的“file:”URI通常表示另一台机器上的不同资源(或根本没有资源)。

其根本原因是文件路径包含正斜杠而不是窗口中的反斜杠。

尝试这样来解决问题:

 "file:" + string.replace("\\", "/"); 

你必须有这样的字符串:

 String windowsPath = file:/C:/Users/sizu/myFile.txt; URI uri = new URI(windowsPath); File file = new File(uri); 

通常,人们做这样的事情:

 String windowsPath = file:C:/Users/sizu/myFile.txt; URI uri = new URI(windowsPath); File file = new File(uri); 

或类似的东西:

 String windowsPath = file:C:\Users\sizu\myFile.txt; URI uri = new URI(windowsPath); File file = new File(uri); 

在将命令行上的URI传递给脚本时,我遇到了相同的“不透明”错误。 这是在Windows上。 我不得不使用正斜杠,而不是反斜杠。 这解决了我。

它需要一个完整的uri类型/协议,例如

 file:/C:/Users/Sumit/Desktop/s%20folder/SAMPLETEXT.txt File file = new File("C:/Users/Sumit/Desktop/s folder/SAMPLETEXT.txt"); file.toURI();//This will return the same string for you. 

我宁愿使用直接字符串来避免创建额外的文件对象。