我在运行时获得了一个jar文件URL:
jar:file:///C:/proj/parser/jar/parser.jar!/test.xml
如何将其转换为有效路径:
C:/proj/parser/jar/parser.jar.
我已经尝试使用File(URI)
,getPath()
,getFile()
徒劳无功。
答案 0 :(得分:34)
如果MS-Windows没有被前导斜杠冒犯,可能会这样做:
final URL jarUrl =
new URL("jar:file:/C:/proj/parser/jar/parser.jar!/test.xml");
final JarURLConnection connection =
(JarURLConnection) jarUrl.openConnection();
final URL url = connection.getJarFileURL();
System.out.println(url.getFile());
答案 1 :(得分:3)
不确定是否会提供您想要的任何确切方法,但这应该让您接近:
import static org.junit.Assert.assertEquals;
import java.net.URL;
import org.junit.Test;
public class UrlTest {
@Test
public void testUrl() throws Exception {
URL jarUrl = new URL("jar:file:/C:/proj/parser/jar/parser.jar!/test.xml");
assertEquals("jar", jarUrl.getProtocol());
assertEquals("file:/C:/proj/parser/jar/parser.jar!/test.xml", jarUrl.getFile());
URL fileUrl = new URL(jarUrl.getFile());
assertEquals("file", fileUrl.getProtocol());
assertEquals("/C:/proj/parser/jar/parser.jar!/test.xml", fileUrl.getFile());
String[] parts = fileUrl.getFile().split("!");
assertEquals("/C:/proj/parser/jar/parser.jar", parts[0]);
}
}
希望这有帮助。
答案 2 :(得分:1)
有些人可能认为这有点'hacky',但它会在那个例子中完成工作,我确信它比在其他建议中创建所有这些对象更能表现得更好。 />
String jarUrl = "jar:file:/C:/proj/parser/jar/parser.jar!/test.xml";
jarUrl = jarUrl.substring(jarUrl.indexOf('/')+1, jarUrl.indexOf('!'));
答案 3 :(得分:1)
此解决方案将处理路径中的空格。
String url = "jar:file:/C:/dir%20with%20spaces/myjar.jar!/resource";
String fileUrl = url.substring(4, url.indexOf('!'));
File file = new File(new URL(fileUrl).toURI());
String fileSystemPath = file.getPath();
或以URL对象开头:
...
String fileUrl = url.getPath().substring(0, url.indexOf('!'));
...
答案 4 :(得分:1)
我必须这样做。
URL url = clazz.getResource(clazz.getSimpleName() + ".class");
String proto = url.getProtocol();
boolean isJar = proto.equals("jar"); // see if it's in a jar file URL
if(isJar)
{
url = new URL(url.getPath()); // this nicely strips off the leading jar:
proto = url.getProtocol();
}
if(proto.equals("file"))
{
if(isJar)
// you can truncate it at the last '!' here
}
else if(proto == "http") {
...
答案 5 :(得分:0)
//This code will work on both Windows and Linux
public String path()
{
URL url1 = getClass().getResource("");
String urs=url1.toString();
urs=urs.substring(9);
String truepath[]=urs.split("parser.jar!");
truepath[0]=truepath[0]+"parser.jar";
truepath[0]=truepath[0].replaceAll("%20"," ");
return truepath[0];
}