Java 如何仅从 jar 中获取 jar URL:包含“!”的 URL 和 jar 中的特定文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/402683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:15:03  来源:igfitidea点击:

How do I get just the jar URL from a jar: URL containing a "!" and a specific file in the jar?

javafileurlpathjar

提问by

I get a jar file url at runtime as:

我在运行时得到一个 jar 文件 url 为:

jar:file:///C:/proj/parser/jar/parser.jar!/test.xml

How can this be converted to a valid path as:

如何将其转换为有效路径:

C:/proj/parser/jar/parser.jar.

I have already tried using File(URI), getPath(), getFile()in vain.

我已经尝试过使用File(URI), getPath(),getFile()徒劳无功。

回答by toolkit

Not sure of any exact method that will give you what you want, but this should get you close:

不确定任何可以为您提供所需内容的确切方法,但这应该会让您接近:

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]);
    }
}

Hope this helps.

希望这可以帮助。

回答by starblue

This might do it, if MS-Windows is not offended by a leading slash:

如果 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());

回答by James Camfield

Some might consider this to be a bit 'hacky', but it'll do the job in that instance and i'm sure it'd perform a damn sight better than creating all those objects in the other suggestions.

有些人可能认为这有点 'hacky',但它会在那种情况下完成工作,我相信它会比在其他建议中创建所有这些对象表现得更好。

String jarUrl = "jar:file:/C:/proj/parser/jar/parser.jar!/test.xml";

jarUrl = jarUrl.substring(jarUrl.indexOf('/')+1, jarUrl.indexOf('!'));

回答by dcstraw

This solution will handle spaces in the path.

此解决方案将处理路径中的空格。

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();

or with a URL object to begin with:

或以 URL 对象开头:

...
String fileUrl = url.getPath().substring(0, url.indexOf('!'));
...

回答by peterk

I just had to do this.

我只是不得不这样做。

        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") {
            ...

回答by Joyal Augustine

  //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];
  }

回答by Hari Chandu Vakacharla

You can do this.This works

你可以这样做。这有效

    ClassLoader loader = this.getClass().getClassLoader();
    URL url = loader.getResource("resource name");
    String[] filePath = null;
    String protocol = url.getProtocol();
    if(protocol.equals("jar")){
        url = new URL(url.getPath());
        protocol = url.getProtocol();
    }
    if(protocol.equals("file")){
        String[] pathArray = url.getPath().split("!");
        filePath = pathArray[0].split("/",2);
    }
    return filePath[1];