java.net.URISyntaxException

java.net.URISyntaxException,java,xml,exception,Java,Xml,Exception,我有这个例外。但这一例外不会再次出现。我想知道这件事的原因 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 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.

发生此异常的原因。如何处理,使其不会复制。

有效的URI不包含反斜杠,如果它包含
,则第一个
前面的字符必须是“协议”

基本上,
“C:\Documents and Settings\All Users\.SF\config\sd.xml”
是一个路径名,而不是有效的URI

如果要将路径名转换为“文件:”URI,请执行以下操作:

File f = new File("C:\Documents and Settings\All Users\.SF\config\sd.xml");
URI u = f.toURI();
这是在Java中将路径名转换为有效URI的最简单、最可靠和可移植的方法。它应该在Windows、Mac、Linux和任何其他支持Java的平台上工作。(涉及对路径名使用字符串重击的其他解决方案是不可移植的。)


但是您需要认识到“file:”uri有许多警告,正如javadocs中对该方法所描述的那样。例如,在一台计算机上创建的“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);
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上。我必须使用正斜杠,而不是反斜杠。这为我解决了问题。

根本原因是windows中的文件路径包含正向斜杠而不是反向斜杠

尝试以下方法来解决问题:

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

它需要具有类型/协议的完整uri e、 g


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

尝试在Windows 8上转义“\”?对于我来说,“file:C:\”方法不起作用,但“file:C:/”起作用。谢谢!:)有一个更好的方法:看