実行時にjarファイルのURLを次のように取得します。
jar:file:///C:/proj/parser/jar/parser.jar!/test.xml
これを次のように有効なパスに変換するにはどうすればよいですか。
C:/proj/parser/jar/parser.jar.
File(URI)
、getPath()
、getFile()
を無駄に使ってみました。
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());
あなたが望むものを与える正確な方法はわかりませんが、これはあなたを近づけるはずです:
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]);
}
}
お役に立てれば。
これは少し「ハッキー」だと考える人もいるかもしれませんが、その場合はうまくいくので、他の提案でこれらすべてのオブジェクトを作成するよりも優れたパフォーマンスを発揮すると確信しています。
String jarUrl = "jar:file:/C:/proj/parser/jar/parser.jar!/test.xml";
jarUrl = jarUrl.substring(jarUrl.indexOf('/')+1, jarUrl.indexOf('!'));
このソリューションは、パス内のスペースを処理します。
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('!'));
...
私はただこれをしなければなりませんでした。
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") {
...
//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];
}
あなたはこれを行うことができます。
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];