当前位置: 动力学知识库 > 问答 > 编程问答 >

java - How to get the path of a directory where my running jar file is?

问题描述:

I try to retrive a path of a directory where my executable jar file is situated.

That means: I have the following structure:

 --> Application (this is a folder somewhere in my file system)

--> application.jar (this is my java application

--> SomeData (folder in the same directory like the application)

--> some other folders

......

When I start my application.jar via command line I want to parse some files inside the SomeData folder.

In http://stackoverflow.com/a/320595/1540630 they already showed how to get the current path of a running jar file but when I execute the statement:

System.out.println(XMLParser.class.getProtectionDomain().getCodeSource().getLocation().getPath());

...I just get the following:

/.../Application/application.jar

But I just want to have:

/.../Application/

Better to say in later steps I need

/.../Application/SomeData/SomeFolder/data.xml

Can someone help me please?

网友答案:

CodeSource.getLocation() gives you a URL, you can then create new URLs relative to that:

URL jarLocation = XMLParser.class.getProtectionDomain().getCodeSource().getLocation();
URL dataXML = new URL(jarLocation, "SomeData/SomeFolder/data.xml");

You can't simply do new File(...getCodeSource().getLocation().getPath()) as a URL path is not guaranteed to be a valid native file path on all platforms. You're much safer sticking with URLs and passing the URL directly to your XML parser if you can, but if you really need a java.io.File then you can use an idiom like this to create one from a URL.

网友答案:

Once you have the jar's location you can use

new File(new File(jarPath).getParent(), "SomeData/SomeFolder/data.xml");
网友答案:

Since you already have the path as a string. You can try the following

String path = XMLParser.class.getProtectionDomain().getCodeSource().getLocation().getPath(); 

String parentFolder = new File(path).getParent();
分享给朋友:
您可能感兴趣的文章:
随机阅读: